dt = datetime.now()
dt.replace(day=28, month=2)
wd = dt.weekday()
sat = dt.replace(day=dt.day+(5-wd))
sun = dt.replace(day=dt.day+(6-wd))
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: day is out of range for month
Thanks,
Luke Skibinski Holt
Probably more of a question for comp.lang.python, but the answer is
pretty simple: import timedelta from datetime as well and then use
sat = dt + timedelta(days = 5 - dt.weekday())
This handles month and year wrapping without any problem.
Cheers,
Malcolm
On Wed, 2006-02-22 at 19:12 -0800, Luke Skibinski Holt wrote:
> dt = datetime.now()
> dt.replace(day=28, month=2)
> wd = dt.weekday()
> sat = dt.replace(day=dt.day+(5-wd))
> sun = dt.replace(day=dt.day+(6-wd))
>>> from datetime import datetime, timedelta
>>> dt = datetime(2006, 2, 28)
>>> wd = dt.weekday()
>>> wd
1
>>> sat = dt + timedelta(5-wd)
>>> sat
datetime.datetime(2006, 3, 4, 0, 0)
HTH,
Russell
--
echo http://russell.rucus.net/spam/ |sed 's,t/.*,t,;P;s,.*//,,;s,\.,@,;'
Luke Skibinski Holt
# Adding to or Subtracting from a Date
# Use the rather nice datetime.timedelta objects
now = datetime.date(2003, 8, 6)
difference1 = datetime.timedelta(days=1)
difference2 = datetime.timedelta(weeks=-2)
print "One day in the future is:", now + difference1
#=> One day in the future is: 2003-08-07
print "Two weeks in the past is:", now + difference2
#=> Two weeks in the past is: 2003-07-23
print datetime.date(2003, 8, 6) - datetime.date(2000, 8, 6)
#=> 1095 days, 0:00:00
Taken directly from:
http://pleac.sourceforge.net/pleac_python/datesandtimes.html
Hope this helps someone.
Luke Skibinski Holt
I like to calculate time differences with a custom SQL query to
optimize speed. The db cursor seems to return a DateTimeDelta object
(is that a psycopg class?) which I need to convert to a
datetime.timedelta to interoperate with other time objects in Django.
On the other hand, if I query DateTimeFields with custom SQL, Django
does automatically convert them to datetime.datetime objects.
Is there any particular reason why time differences returned by SQL
queries shouldn't be converted to datetime.timedelta objects by Django?
Here's what I have to do now (better ideas appreciated):
class Event(meta.Model):
starttime = meta.DateTimeField()
endtime = meta.DateTimeField()
def duration_minutes(self):
cursor = db.cursor()
cursor.execute("SELECT endtime-starttime FROM myapp_events
WHERE id = %s", [self.id])
try:
return cursor.fetchone()[0].minutes
# fetchone() returns e.g. (<DateTimeDelta object for
'02:54:00.00' at b756efc0>,)
except:
return 0.0
def duration(self):
from datetime import timedelta
return timedelta(minutes=self.duration_minutes())