简体   繁体   中英

Convert json field to datetime in Python

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!

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:

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM