2

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
Satya Dev Yadav
  • 143
  • 3
  • 13
  • 1
    What is the issue you're facing? – FObersteiner Jul 19 '21 at 06:06
  • Does this answer your question? [How do I parse an ISO 8601-formatted date?](https://stackoverflow.com/questions/127803/how-do-i-parse-an-iso-8601-formatted-date) – FObersteiner Jul 19 '21 at 06:08
  • What it is the problem? Maybe if you write also what you tried (with actual result, and expected result), it will help us to understand better your problem. Python3.6 now is *old*. If you can update to Python 3.7 (or later), you have *fromisoformat* functions in datetime module – Giacomo Catenazzi Jul 19 '21 at 06:16
  • @MrFuppes I am not getting how to get the object using strptime method. – Satya Dev Yadav Jul 19 '21 at 06:26

1 Answers1

3

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")
igrinis
  • 12,398
  • 20
  • 45