gpt4 book ai didi

python - 在Python中,如何仅使用datetime包获取本地化时间戳?

转载 作者:太空宇宙 更新时间:2023-11-03 16:12:16 24 4
gpt4 key购买 nike

我有一个以秒为单位的unix时间戳(例如1294778181),我可以使用它转换为UTC

from datetime import datetime
datetime.utcfromtimestamp(unix_timestamp)

问题是,我想获取 'US/Eastern' 中的相应时间(考虑任何 DST),但我无法使用 pytz 和其他实用程序。

我只能使用datetime

这可能吗?谢谢!

最佳答案

最简单但不是 super 智能的解决方案是使用 timedelta

import datetime
>>> now = datetime.datetime.utcnow()

美国/东部时间比 UTC 晚 5 小时,所以让我们创建 5 小时作为 timedelta 对象并将其设置为负数,这样当读回我们的代码时,我们可以看到偏移量为 -5,并且没有什么神奇之处决定何时添加和何时减去时区偏移

>>> eastern_offset = -(datetime.timedelta(hours=5))
>>> eastern = now + eastern_offset
>>> now
datetime.datetime(2016, 8, 26, 20, 7, 12, 375841)
>>> eastern
datetime.datetime(2016, 8, 26, 15, 7, 12, 375841)

如果我们想修复 DST,我们会通过像这样的平滑来运行日期时间(不完全准确,时区不是我的专业知识(现在谷歌搜索一下,它每年都会变化,恶心))

if now.month > 2 and now.month < 12:
if (now.month == 3 and now.day > 12) or (now.month == 11 and now.day < 5):
eastern.offset(datetime.timedelta(hours=5))

您甚至可以更详细地了解,添加时间,了解每年到底如何变化......我不会详细介绍所有这些:)

关于python - 在Python中,如何仅使用datetime包获取本地化时间戳?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39171908/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com