3

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
4
  • 1
    What is the issue you're facing? Commented Jul 19, 2021 at 6:06
  • Does this answer your question? How do I parse an ISO 8601-formatted date? Commented Jul 19, 2021 at 6: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 Commented Jul 19, 2021 at 6:16
  • @MrFuppes I am not getting how to get the object using strptime method. Commented Jul 19, 2021 at 6:26

1 Answer 1

4

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")
Sign up to request clarification or add additional context in comments.

2 Comments

But I want to retain the timezone info. strptime("2021-07-04T00:00:00+0200", "%Y-%m-%dT%H:%M:%S%z") works in Python 3.6 But if there is colon in time zone (like +02:00) it not works
OK means, need to do the things manually. There is not any direct way!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.