0

I get time data from API response like '2020-02-25T20:53:06.706401+07:00'. Now I want to convert to %Y-%m-%d %H:%M:%s format. But I do not know exactly standard format of that time data.

Help me find the time format!

Huy Vu The
  • 123
  • 2
  • 2
  • 10

2 Answers2

2

In your case you can use datetime.fromisoformat:

from datetime import datetime

datetime_object = datetime.fromisoformat("2020-02-25T20:53:06.706401+07:00")
print(datetime_object.strftime("%Y-%m-%d %H:%M:%s"))

Prints

2020-02-25 20:53:1582656786

Other options:

hurlenko
  • 1,363
  • 2
  • 12
  • 17
0

You can convert to a datetime object and then optionally recreate the string in a new format as follows:

from datetime import datetime

d = "2020-02-25T20:53:06.706401+07:00"
dt = datetime.strptime(d, "%Y-%m-%dT%H:%M:%S.%f%z")
# Note the capital S
new = dt.strftime("%Y-%m-%d %H:%M:%S")

However the new value here has lost the timezone offset information. I assume that's OK for you. I also used %S instead of %s since I assume that's really what you want. The lowercase %s wouldn't really make sense, and is also not truly supported by Python.

totalhack
  • 2,298
  • 17
  • 23