[Tutor] Date comparison across time zones
Martin Walsh
mwalsh at mwalsh.org
Tue Jan 13 20:18:21 CET 2009
frenc1z 1z wrote:
> Hello,
> I would like to compare some dates (date+time really). The dates all
> have the following RFC2822 format:
>
> Eg. is d1 < d2?
> d1 = "Tue, 13 Jan 2009 03:27:29 -0800"
> d2 = "Tue, 13 Jan 2009 02:40:00 -0600"
>
> My thinking is that I first need to make these two dates comparable, and
> eliminate the impact of time zone and dst. Understand that I can acheive
> this using strptime.
>
> Been trying to parse these dates as follows: print
> datetime.strptime("Tue, 13 Jan 2009 02:40:00 -0800", "%a, %d %b %Y
> %H:%M:%S %z").
>
> I get the following error on the conversion "ValueError: 'z' is a bad
> directive in format '%a, %d %b %Y %H:%M:%S %z'".
>
I'm not sure how one would accomplish this with only the stdlib, but
there are at least two 3rd party modules which you may find useful.
dateutil: http://labix.org/python-dateutil
mx.DateTime: http://www.egenix.com/products/python/mxBase/mxDateTime/
Each of these implement a timezone aware date-string parser, here is an
(untested) example or two:
d1 = "Tue, 13 Jan 2009 03:27:29 -0800"
d2 = "Tue, 13 Jan 2009 02:40:00 -0600"
from dateutil import parser
dparser = parser.parser()
p1 = dparser.parse(d1)
p2 = dparser.parse(d2)
print p1 < p2
from mx.DateTime import DateTimeFrom
m1 = DateTimeFrom(d1)
m2 = DateTimeFrom(d2)
print m1 < m2
HTH,
Marty
More information about the Tutor
mailing list