Python datetime 和 tzinfo 对象(更改分钟而不是小时)

标签 python datetime pytz

我正在尝试将 tzinfo 应用于日期时间对象。

In [1]: from datetime import datetime
In [2]: import pytz

In [3]: london = pytz.timezone("Europe/London")
In [4]: london
Out[5]: <DstTzInfo 'Europe/London' LMT-1 day, 23:59:00 STD>

In [6]: localized_date_object = datetime(2016, 1, 1, 11, 30, 0, 5000, london)
In [7]: localized_date_object
Out[8]: datetime.datetime(2016, 1, 1, 11, 30, 0, 5000, tzinfo=<DstTzInfo 'Europe/London' LMT-1 day, 23:59:00 STD>)

In [9]: utc_date_object = localized_date_object.astimezone(pytz.utc)
In [10]: utc_date_object
Out[11]: datetime.datetime(2016, 1, 1, 11, 31, 0, 5000, tzinfo=<UTC>)

In [16]: paris = pytz.timezone("Europe/Paris")
In [17]: localized_date_object = datetime(2016, 1, 1, 11, 30, 0, 5000, paris)
In [18]: utc_date_object = localized_date_object.astimezone(pytz.utc)
In [19]: utc_date_object
Out[19]: datetime.datetime(2016, 1, 1, 11, 21, 0, 5000, tzinfo=<UTC>)

如您所见,它将增量应用于分钟而不是小时。
有人可以向我解释我在这里做错了什么。

最佳答案

pytz 文档说:

This library only supports two ways of building a localized time. The first is to use the localize() method provided by the pytz library. This is used to localize a naive datetime (datetime with no timezone information):

The second way of building a localized time is by converting an existing localized time using the standard astimezone() method:

Unfortunately using the tzinfo argument of the standard datetime constructors ‘’does not work’’ with pytz for many timezones.

在提供的代码示例中,您尝试使用 tzinfo 参数而不是 localize()

>>> london = pytz.timezone("Europe/London")

>>> datetime.datetime(2016, 1, 1, 11, 30, 0, 5000, london) # This is incorrect
datetime.datetime(2016, 1, 1, 11, 30, 0, 5000, tzinfo=<DstTzInfo 'Europe/London' LMT-1 day, 23:59:00 STD>)

>>> london.localize(datetime.datetime(2016, 1, 1, 11, 30, 0, 5000)) # This is correct
datetime.datetime(2016, 1, 1, 11, 30, 0, 5000, tzinfo=<DstTzInfo 'Europe/London' GMT0:00:00 STD>)

关于Python datetime 和 tzinfo 对象(更改分钟而不是小时),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40740316/

相关文章:

python - 如何在Python 2中调用logging.setLogRecordFactory?

php - 如何在 php 中找到日期时间类型和当前日期/时间之间的差异?

android sqlite 获取当天有效的行

python - 为什么 datetime.now() 和 datetime.utcnow() 返回不同的时间戳

Python while语句错误

python - 本地机与多个独立进程的进程间通信(1个服务器,n个客户端)

python - 如何根据特定列中的值对 pandas 数据文件中的字符串进行排序?

python - 从 CET/CEST 到 UTC 的时间序列转换

python - 如何根据 UTC 偏移量选择时区?

python - 如何在Python中转换为UTC后完全删除tzinfo?