Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string date with timezone to datetime?

Tags:

python

date

I have date in string:

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

and I use (according to https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior):

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?

like image 427
Nips Avatar asked Nov 14 '25 19:11

Nips


2 Answers

%z is the +0200, %Z is CEST. Therefore:

>>> s = "Tue Oct 04 2016 12:13:00 GMT+0200 (CEST)"
>>> datetime.strptime(s, '%a %b %d %Y %H:%M:%S GMT%z (%Z)')
datetime.datetime(2016, 10, 4, 12, 13, tzinfo=datetime.timezone(datetime.timedelta(0, 7200), 'CEST'))

I also replaced your %m with %d; %m is the month, numerically, so in your case 04 would be parsed as April.

like image 115
L3viathan Avatar answered Nov 17 '25 08:11

L3viathan


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'
like image 39
Mazdak Avatar answered Nov 17 '25 08:11

Mazdak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!