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?
If you are on Linux, then you can use the external
date
command to dwim:This is of course less portable than dateutil, but slightly more flexible, because
date
will also accept inputs like "yesterday" or "last year" :-)Here is a fix of the
"%z"
issue for Python 2.7 and earlierInstead of using:
Use the
timedelta
to account for the timezone, like this:Note that the dates would be converted to
GMT
, which would allow doing date arithmetic without worrying about time zones.One liner for old Pythons out there. You can multiply a timedelta by 1/-1 depending on +/- sign, as in:
%z
is supported in Python 3.2+:On earlier versions:
where
FixedOffset
is a class based on the code example from the docs:The problem with using dateutil is that you can't have the same format string for both serialization and deserialization, as dateutil has limited formatting options (only
dayfirst
andyearfirst
).In my application, I store the format string in .INI file, and each deployment can have its own format. Thus, I really don't like the dateutil approach.
Here's an alternative method that uses pytz instead:
You can use the parse function from dateutil:
This way you obtain a datetime object you can then use.
As answered, dateutil2.0 is written for Python 3.0 and does not work with Python 2.x. For Python 2.x dateutil1.5 needs to be used.