首页 > 解决方案 > 将 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

标签: pythondatetime

解决方案


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

推荐阅读