Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python. Converting string into datetime throws ValueError [duplicate]

I have the string:

import datetime
time = "2016-02-01 19:14:54+02:00"

And trying to convert it to datetime obj:

result = datetime.datetime.strptime(time, "%Y-%m-%d %H:%M:%S%z")

It throws exception:

ValueError: time data '2016-02-01 19:14:54+02:00' does not match format '%Y-%m-%d %H:%M:%S%z'

Could you please help me what is wrong here?

like image 232
Bazaka Bazaka Avatar asked Jun 23 '26 19:06

Bazaka Bazaka


1 Answers

Timezone offset %z should not have : between hours and minutes according to the python strptime specification.

>>>> datetime.datetime.strptime("2016-02-01 19:14:54+02:00", "%Y-%m-%d %H:%M:%S%z")
ValueError: time data '2016-02-01 19:14:54+02:00' does not match format '%Y-%m-%d %H:%M:%S%z'

>>> datetime.datetime.strptime("2016-02-01 19:14:54+0200", "%Y-%m-%d %H:%M:%S%z")
datetime.datetime(2016, 2, 1, 19, 14, 54, tzinfo=datetime.timezone(datetime.timedelta(0, 7200)))
like image 152
Håken Lid Avatar answered Jun 26 '26 20:06

Håken Lid



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!