datetime.combine()和pytz.localize()之间的区别 [英] Difference between datetime.combine() and pytz.localize()

查看:224
本文介绍了datetime.combine()和pytz.localize()之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对以下行为感到困惑。假设我使用 datetime.combine() 来构造一个时区感知对象:

I am a bit puzzled by the following behavior. Suppose I use datetime.combine() to construct a timezone-aware object:

>>> date
datetime.date(2018, 10, 17)
>>> time
datetime.time(6, 0)
>>> tz
<DstTzInfo 'Europe/Berlin' LMT+0:53:00 STD>
>>> datetime.combine(date, time, tzinfo=tz)
datetime.datetime(2018, 10, 17, 6, 0, tzinfo=<DstTzInfo 'Europe/Berlin' LMT+0:53:00 STD>)

或我使用 pytz.localize() 进行相同操作:

or I use pytz.localize() to do the same:

>>> tz.localize(datetime.combine(date, time))
datetime.datetime(2018, 10, 17, 6, 0, tzinfo=<DstTzInfo 'Europe/Berlin' CEST+2:00:00 DST>)

请注意 tzinfo 的时区名称和偏移量已更改。我找不到适合该行为的文档。 pytz 文档说


不幸的是,使用标准datetime构造函数的tzinfo参数在很多时区都无法使用pytz。

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

那么,这到底是怎么回事? (有些相关的问题是此处此处。)

So what exactly is going on here? (Somewhat related questions are here or here.)

推荐答案

您刚刚(再次)发现,在创建支持时区的日期时间时,绝对不要直接添加时区信息。始终使用 tz.localize()

You just found out (again) that you should never directly add timezone information when creating timezone-aware datetimes. Always use tz.localize().

您看到的问题是因为 datetime .combine 不会将 tzinfo 对象调整为实际的日期时间。仍然假设该时区的第一个有效日期的时区信息是1800年代末,并且恰好是UTC的 0:53:00

The problem you are seeing is because datetime.combine doesn't adjust the tzinfo object to the actual datetime. It still assumes the timezone information of the first valid date in this timezone, which was in the late 1800's and happened to be 0:53:00 off from UTC.

这篇关于datetime.combine()和pytz.localize()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆