如何转换字符串“ 2020-07-29 10:27:08 + 02:00”格式为“ 2020-07-29T08:27:16.494Z”? [英] How to convert string "2020-07-29 10:27:08+02:00" to this format "2020-07-29T08:27:16.494Z"?

查看:182
本文介绍了如何转换字符串“ 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 (我知道两个字符串的值是不同的,只是关于格式)。

I need to have "2020-07-29 10:27:08+02:00" in this format "2020-07-29T08:27:16.494Z" (I know the value of both strings is different, it is only about the format).

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

I tried this so far:

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


推荐答案

使用标准方法,您不会得到毫秒和 Z,因此我们需要即兴创作。

With standard methods, you don't get milliseconds and 'Z', so we need to improvise. Here's a way to do it.

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

这篇关于如何转换字符串“ 2020-07-29 10:27:08 + 02:00”格式为“ 2020-07-29T08:27:16.494Z”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆