【问题标题】:want to convert json timestamp into normal timestamp (CST Hrs) in python想在python中将json时间戳转换为普通时间戳(CST Hrs)
【发布时间】:2021-06-06 02:01:06
【问题描述】:

我正在使用 python 下载一个包含时间戳的 json 文件。但我得到的时间戳低于格式

 `2021-04-01T21:43:52.757Z`

想要转换为普通时间戳 (CST Hrs)。我还看到手动比较报告时,时间增加了 4 小时。

 `4/1/2021  5:43:53 PM`

与 json 文件条目相比,上述时间减少了 4 小时。请给我建议。

【问题讨论】:

标签: python json


【解决方案1】:

您需要使用 python 的datetime 模块来处理这个问题。字符串中的 Z 实际上表示时区 0 或 UTC 时间,比 CST 早 6 小时而不是 4:

import datetime

date_object = datetime.datetime.strptime(
    "2021-04-01T21:43:52.757Z", "%Y-%m-%dT%H:%M:%S.%fZ"
)

date_object = date_object - datetime.timedelta(hours=6)

print(
    f"{date_object.month}/{date_object.day}/{date_object.year} {date_object.strftime('%I:%M:%S %p')}"
)

这将给出这个输出:

4/1/2021 03:43:52 PM

如果您想要非零填充日期,则必须使用 f 字符串,因为根据 docs,它在 datetime 中不可用

您可以使用pytz 模块直接处理时区,如果您愿意,也可以不对其进行硬编码。或者,如果您使用的是 python 3.9,您可以使用 timezone 对象自己创建时区

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-10
    • 1970-01-01
    • 2017-12-03
    • 2013-02-08
    • 1970-01-01
    • 2012-08-07
    • 2020-01-09
    • 2018-07-15
    相关资源
    最近更新 更多