Parsing time string in Python

xiaohan2012 picture xiaohan2012 · May 8, 2012 · Viewed 110.6k times · Source

I have a date time string that I don't know how to parse it in Python.

The string is like this:

Tue May 08 15:14:45 +0800 2012

I tried

datetime.strptime("Tue May 08 15:14:45 +0800 2012","%a %b %d %H:%M:%S %z %Y")

but Python raises

'z' is a bad directive in format '%a %b %d %H:%M:%S %z %Y'

According to Python doc:

%z UTC offset in the form +HHMM or -HHMM (empty string if the the object is naive).

What is the right format to parse this time string?

Answer

eumiro picture eumiro · May 8, 2012

datetime.datetime.strptime has problems with timezone parsing. Have a look at the dateutil package:

>>> from dateutil import parser
>>> parser.parse("Tue May 08 15:14:45 +0800 2012")
datetime.datetime(2012, 5, 8, 15, 14, 45, tzinfo=tzoffset(None, 28800))