在Python中,如何只用datetime包获取本地化的时间戳?
In Python, how to get a localized timestamp with only the datetime package?
我有一个以秒为单位的 unix 时间戳(例如 1294778181
),我可以使用
将其转换为 UTC
from datetime import datetime
datetime.utcfromtimestamp(unix_timestamp)
问题是,我想在 'US/Eastern'
中获取相应的时间(考虑任何夏令时),但我无法使用 pytz
和其他实用程序。
只有 datetime
对我可用。
这可能吗?
谢谢!
最简单但不是超级智能的解决方案是使用 timedelta
import datetime
>>> now = datetime.datetime.utcnow()
US/Eastern 比 UTC 晚 5 小时,所以我们只创建 thouse 五个小时作为 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)
如果我们想修复夏令时,我们会 运行 通过这样平滑的日期时间(不完全准确,时区不是我的专长(现在谷歌搜索了一下,它每年都在变化,糟糕))
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))
您甚至可以了解更多细节,增加小时数,了解它每年的确切变化......我不打算经历所有这些:)
我有一个以秒为单位的 unix 时间戳(例如 1294778181
),我可以使用
from datetime import datetime
datetime.utcfromtimestamp(unix_timestamp)
问题是,我想在 'US/Eastern'
中获取相应的时间(考虑任何夏令时),但我无法使用 pytz
和其他实用程序。
只有 datetime
对我可用。
这可能吗? 谢谢!
最简单但不是超级智能的解决方案是使用 timedelta
import datetime
>>> now = datetime.datetime.utcnow()
US/Eastern 比 UTC 晚 5 小时,所以我们只创建 thouse 五个小时作为 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)
如果我们想修复夏令时,我们会 运行 通过这样平滑的日期时间(不完全准确,时区不是我的专长(现在谷歌搜索了一下,它每年都在变化,糟糕))
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))
您甚至可以了解更多细节,增加小时数,了解它每年的确切变化......我不打算经历所有这些:)