[英]Convert json field to datetime in Python
I get time data from API response like '2020-02-25T20:53:06.706401+07:00'
.我从 API 响应中获取时间数据,例如'2020-02-25T20:53:06.706401+07:00'
。 Now I want to convert to %Y-%m-%d %H:%M:%s
format.现在我想转换为%Y-%m-%d %H:%M:%s
格式。 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 :在您的情况下,您可以使用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:其他选项:
Use datetime.strptime which parses the string according to format使用datetime.strptime根据格式解析字符串
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.但是这里的new
值丢失了时区偏移信息。 I assume that's OK for you.我想这对你来说没问题。 I also used %S
instead of %s
since I assume that's really what you want.我还使用了%S
而不是%s
因为我认为这确实是您想要的。 The lowercase %s
wouldn't really make sense, and is also not truly supported by Python .小写的%s
没有任何意义,并且Python 也不真正支持。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.