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

标签 python date datetime

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

相关文章:

Python/Flask 表单错误 - AttributeError : 'unicode' object has no attribute '__call__'

java - 在 Java 中使用 Duration 对象将天、分钟、小时转换为秒失败

MySQL 5默认日期为空,无法插入日期= ''为什么?

sql - 如何在 SQL Server 中截断日期时间?

python - Django Rest Framework 自定义响应消息

python - 有没有一种方法可以不慢地增加 numpy 数组?

python - OpenCV/Python - 从灰度图像中查找灰度图案矩形的角坐标?

javascript - moment.js 通过 .diff() 比较日期

c# - 更改 .net DateTime 的 Dapper 映射以使用 DbType DateTime2 并再次恢复它

c# - 日、月、日、年的日期格式