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

时间:2020-07-29 08:57:35

标签: python python-3.x datetime

我需要使用“ 2020-07-29T08:27:16.494Z”格式的“ 2020-07-29 10:27:08 + 02:00”(我知道两个字符串的值都不同,仅与格式有关。

到目前为止,我已经尝试过:

{{1}}

1 个答案:

答案 0 :(得分:1)

使用标准方法,您不会得到毫秒和“ 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