Wednesday, January 27, 2010

Python datetime module

Steven Lott recommends on SO, to use the standard library. In this case, the module of interest is datetime. Normally you would use it something like this:

>>> import datetime
>>> d = datetime.date(2010, 1, 27)
>>> d
datetime.date(2010, 1, 27)
>>> t = datetime.time(12, 30)
>>> t
datetime.time(12, 30)
>>> datetime.datetime.combine(d, t)
datetime.datetime(2010, 1, 27, 12, 30)


The fields are y m d h m s, plus microseconds.

"A datetime object is a single object containing all the information from a date object and a time object. Like a date object, datetime assumes the current Gregorian calendar extended in both directions; like a time object, datetime assumes there are exactly 3600*24 seconds in every day."


What time is it now?

>>> n = datetime.datetime.now()
>>> n
datetime.datetime(2010, 1, 27, 17, 41, 47, 94035)
>>> n.__repr__()
'datetime.datetime(2010, 1, 27, 17, 41, 47, 94035)'
>>> print n
2010-01-27 17:41:47.094035
>>> n.ctime()
'Wed Jan 27 17:41:47 2010'


The format returned by print generally follows the ISO-8601 format, except for the microseconds, which I don't find in the wikipedia entry describing ISO-8601.

The method strftime() takes a large number of format codes to control its behavior.

>>> for c in 'aAbBcdfHIjmMyY':
... fc = '%' + c
... print fc, n.strftime(fc)
...
%a Wed
%A Wednesday
%b Jan
%B January
%c Wed Jan 27 17:41:47 2010
%d 27
%f 094035
%H 17
%I 05
%j 027
%m 01
%M 41
%y 10
%Y 2010


Another useful object is the timedelta.

"A timedelta object represents a duration, the difference between two dates or times."


>>> n = datetime.date.today()
>>> my_bd = datetime.date(1955, 10, 24)
>>> diff = n - my_bd
>>> diff
datetime.timedelta(19819)
>>> d = 7 + 30 + 31 + 27 # days since my last bd
>>> 54*365 + 14 + d # years (in days) + leap days
19819


One of the issues that always comes up is time zones. Time zones are complicated, because their behavior is variable and needs to be specified. So we need yet another class object to deal with them. I'll look at that another time.