python - 如何将字符串“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
解决方案
使用标准方法,您不会得到毫秒和“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
推荐阅读
- dataframe - 使用其他列值作为参考替换行中的某些值
- node.js - 功能认证中间件节点
- c# - 数据模型依赖于另一个数据模型的属性时的数据绑定
- elasticsearch - elasticsearch中关键字类型为文本时如何使用term查询
- android - 如何动态更改依赖项?
- .net - Grafana PromQL 无法读取未定义的属性“结果”
- flutter - 自定义原材料按钮 - Flutter
- angular - 尝试 npm install 时标签名称“file-saver@2.0.1”无效
- angular - RXJS 和 typescript:有条件地使用服务器和客户端代码执行工作
- c# - 如何在 ASP.NET Core 中为 React SPA 自定义身份控制器?