Nips Nips - 23 days ago 4
Python Question

How to convert string date with timezone to datetime?

I have date in string:

Tue Oct 04 2016 12:13:00 GMT+0200 (CEST)

and I use (according to

datetime.strptime(datetime_string, '%a %b %m %Y %H:%M:%S %z %Z')

but I get error:

ValueError: 'z' is a bad directive in format '%a %b %m %Y %H:%M:%S %z %Z'

How to do it correctly?


python datetime can't parse the GMT part (You might want to specify it manually in your format). You can use dateutil instead:

In [16]: s = 'Tue Oct 04 2016 12:13:00 GMT+0200 (CEST)'

In [17]: from dateutil import parser

In [18]: parser.parse(s)
Out[18]: d = datetime.datetime(2016, 10, 4, 12, 13, tzinfo=tzoffset(u'CEST', -7200))
In [30]: d.utcoffset()
Out[30]: datetime.timedelta(-1, 79200)

In [31]: d.tzname()
Out[31]: 'CEST'