【问题标题】:In Python, how to get a localized timestamp with only the datetime package?在 Python 中,如何仅使用 datetime 包获取本地化时间戳?
【发布时间】:2017-01-03 10:58:59
【问题描述】:

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

将其转换为 UTC
from datetime import datetime
datetime.utcfromtimestamp(unix_timestamp)

问题是,我想在'US/Eastern' 中获得相应的时间(考虑到任何夏令时),我不能使用pytz 和其他实用程序。

我只能使用datetime。

这可能吗? 谢谢!

【问题讨论】:

  • 您可以编写自己的函数来添加/减去 timedelta
  • 是的,我想避免这种情况,因为您需要跟踪正确的偏移量对吗?
  • 是的,但我想不出另一种方式:/ 你总是可以编写自己的 pytz :D github.com/newvem/pytz/tree/master/pytz
  • 你能根据你的 timedelta 想法写一个答案吗?

标签: python datetime epoch python-datetime


【解决方案1】:

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

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

US/Eastern 比 UTC 晚 5 小时,所以让我们创建 thouse 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,我们会像这样通过 smoeth 运行日期时间(不完全准确,时区不是我的专长(谷歌搜索一下,现在每年都在变化,呸))

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))

你甚至可以更详细,增加小时数,了解它每年的具体变化......我不会经历所有这些:)

【讨论】:

  • 很好,但这是否考虑到夏令时?
  • 不幸的是它没有。当日期时间的不带年份的日期在另外两个日期时间之间时,如果条件应用另一个小时偏移量,可以修复它
  • @Noobie 我编辑了我的答案,对如何进行 DST 有一个广泛的想法,但如果你希望它始终准确,那就相当复杂了。这就是我们有 pytz 的原因
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-20
  • 2020-09-18
  • 2021-10-21
  • 2016-10-03
  • 2017-06-15
  • 2019-01-05
  • 2019-06-05
相关资源
最近更新 更多