fields fields - 8 months ago 36
Python Question

How to parse dates with -0400 timezone string in python?

I have a date string of the form '2009/05/13 19:19:30 -0400'. It seems that previous versions of python may have supported a %z format tag in strptime for the trailing timezone specification, but 2.6.x seems to have removed that.

What's the right way to parse this string into a datetime object?


You can use the parse function from dateutil:

>>> from dateutil.parser import parse
>>> d = parse('2009/05/13 19:19:30 -0400')
>>> d
datetime.datetime(2009, 5, 13, 19, 19, 30, tzinfo=tzoffset(None, -14400))

This way you obtain a datetime object you can then use.

UPDATE: As answered dateutil2.0 is written for python3.0 and does not work with python2.x. For python2.x dateutil1.5 needs to be used.