I am facing a issue while converting a iso format datetime string to datetime object in Python 3.6 without loosing the timezone info. The string is like this.
2021-07-04T00:00:00+02:00
I tried datetime.datetime.strptime method. But unable to set the correct format string.
datetime.datetime.strptime( "2021-07-04T00:00:00+02:00", "%Y-%m-%dT%H:%M:%S%z")
If the datetime string is in this format it works:
datetime.strptime("2021-07-04T00:00:00+0200", "%Y-%m-%dT%H:%M:%S%z")
But in this format, don't work:
datetime.datetime.strptime( "2021-07-04T00:00:00+02:00", "%Y-%m-%dT%H:%M:%S%z")
And I have the datetime in this format:
2021-07-04T00:00:00+02:00
For Python 3.7+ you can use datetime.datetime.fromisoformat() function, also
strptime("2021-07-04T00:00:00+02:00", "%Y-%m-%dT%H:%M:%S%z") will work fine.
For Python 3.6 and lower the time zone format is expected to be ±HHMM. So you will have to transform the string before using strptime (remove the last semicolon).
For example:
tz_found = t_str.find('+')
if tz_found!=-1 and t_str.find(':', tz_found)!=-1:
t_str = t_str[:tz_found+3] + t_str[tz_found+4:tz_found+6]
result = datetime.datetime.strptime( t_str, "%Y-%m-%dT%H:%M:%S%z")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With