gpt4 book ai didi

Python date.today() 不返回本地日期

转载 作者:行者123 更新时间:2023-11-28 16:19:54 26 4
gpt4 key购买 nike

我在美国东部时间并尝试使用 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/

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