Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert iso format datetime string to datetime object in Python

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
like image 251
Satya Dev Yadav Avatar asked Apr 29 '26 02:04

Satya Dev Yadav


1 Answers

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")
like image 167
igrinis Avatar answered May 01 '26 20:05

igrinis



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!