首页 > 解决方案 > 如何将字符串“2020-07-29 10:27:08+02:00”转换为这种格式“2020-07-29T08:27:16.494Z”?

问题描述

我需要“2020-07-29 10:27:08+02:00”这种格式“2020-07-29T08:27:16.494Z”(我知道两个字符串的值不同,它只是大约格式)。

到目前为止我试过这个:

dt = datetime.strptime(realTimeStamp,"%d/%b/%Y:%H:%M:%S%z")
print(dt.date()) # results to 2020-07-27

标签: pythonpython-3.xdatetime

解决方案


使用标准方法,您不会得到毫秒和“Z”,因此我们需要即兴发挥。这是一种方法。

from datetime import datetime, timezone

s = "2020-07-29 10:27:08.494+02:00"

# parse to datetime object including the UTC offset and convert to UTC
dt = datetime.fromisoformat(s).astimezone(timezone.utc)

# format to string, excluding microseconds and UTC offset
out = dt.strftime('%Y-%m-%dT%H:%M:%S')
# add the microseconds, rounded to milliseconds
out += f"{dt.microsecond/1e6:.3f}".lstrip('0')
# add UTC offset, Z for zulu/UTC - we know it's UTC from conversion above
out += 'Z'

这会给你

print(out)
>>> 2020-07-29T08:27:08.494Z

推荐阅读