我在美国东部时间并尝试使用 date.today()
,但它会在第二天返回。文档说明它应该是本地时间。有谁知道如何让它返回我的本地 (EST) 日期?
classmethod date.today() Return the current local date. This is equivalent to date.fromtimestamp(time.time()).
https://docs.python.org/2/library/datetime.html#date-objects
更新:澄清一下,除了我在美国东部标准时间晚上 10 点左右尝试时,它大部分时间都有效。我用 time.strftime('%X %x %Z')
检查了我的时区,它看起来像 UTC。鉴于这种情况,我如何获得今天的日期?请注意,我想在获取 EST 日期的同时保留系统 UTC。
最佳答案
如果你不介意使用 pytz
:
from datetime import datetime, date
from pytz import timezone
datetime.now(timezone('US/Eastern'))
请注意 python datetime module明确推荐 pytz
(但也包含一个“大部分时间”有效的示例):
pytz
The standard library has no tzinfo instances, but there exists a third-party library which brings the IANA timezone database (also known as the Olson database) to Python: pytz.
pytz contains up-to-date information and its usage is recommended.
明确地将其转换为日期
:
date.fromtimestamp(datetime.now(timezone('US/Eastern')).timestamp())
或者如果您使用的是 python < 3.3(因为 datetime.timestamp
是 4 年前发布的,所以早期版本可能没有它):
from datetime import timezone as datetime_timezone
now = datetime.now(timezone('US/Eastern'))
ts = (now - datetime(1970, 1, 1, tzinfo=datetime_timezone.utc)).total_seconds()
date.fromtimestamp(ts)
关于Python date.today() 不返回本地日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41195130/