我需要使用“ 2020-07-29T08:27:16.494Z”格式的“ 2020-07-29 10:27:08 + 02:00”(我知道两个字符串的值都不同,仅与格式有关。
到目前为止,我已经尝试过:
{{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