python - 将 json UTC 时间格式转换为 CST - 在 python 中
问题描述
我已经完成了将 json UTC 时间格式转换为 CST 的代码。但是我在输入文件中看到了 2 种不同的 UTC 时间格式。我使用以下代码转换为 CST。
`date_object = datetime.datetime.strptime(sline[i], "%Y-%m-%dT%H:%M:%S.%fZ")`
这适用于
`2021-06-11T19:30:32.42Z`
但不为
`2021-06-11T15:26:31Z`
如何为同一字段设置多种格式的 datatime.striptime?有什么建议???
谢谢
..-Prasanna.K
解决方案
dateutil的解析器在处理不同的输入格式方面做得很好:
import dateutil
ts = ["2021-06-11T19:30:32.42Z", "2021-06-11T15:26:31Z"]
to_tz = dateutil.tz.gettz("US/Central")
# to datetime / UTC and then to desired time zone in one step:
dts = [dateutil.parser.parse(s).astimezone(to_tz) for s in ts]
# dts
# [datetime.datetime(2021, 6, 11, 14, 30, 32, 420000, tzinfo=tzfile('/usr/share/zoneinfo/US/Central')),
# datetime.datetime(2021, 6, 11, 10, 26, 31, tzinfo=tzfile('/usr/share/zoneinfo/US/Central'))]
for d in dts:
print(d)
# 2021-06-11 14:30:32.420000-05:00
# 2021-06-11 10:26:31-05:00
推荐阅读
- python - 使用 QGraphicsView 场景放大鼠标位置
- android-studio - 禁用/隐藏内部类的 IDE 折叠按钮
- c# - Visual Studio C#:无法使用 IntelliTest 对类中的方法生成单元测试?
- php - Require_once php 在托管程序中不起作用
- php - preg_match_all 使用 php preg_match_all 从 httpd-vhosts.conf 文件 xampp 获取虚拟主机列表
- json - 在 aws 中拆分和合并批处理作业中的 json 文件
- javascript - 如何创建 NodeList 实时循环长度检查器
- laravel - Laravel 在 null 上调用成员函数 validate()
- python - 训练二进制分类器 Tensorflow 时出现错误“不支持将字符串转换为浮点数”?
- azure-ad-b2c - 出现间歇性 ADB2C“错误请求”错误