`datetime.now(pytz_timezone)'何时失败? [英] when does `datetime.now(pytz_timezone)` fail?

查看:266
本文介绍了`datetime.now(pytz_timezone)'何时失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

delorean docs 以这种方式显示获取指定时区中的当前时间 使用 datetime

delorean docs show this way to get the current time in a given timezone using datetime:

from datetime import datetime
from pytz import timezone

EST = "US/Eastern"
UTC = "UTC"

d = datetime.utcnow()
utc = timezone(UTC)
est = timezone(EST)
d = utc.localize(d)
d = est.normalize(EST)

,并将其与基于偏爱的代码进行比较:

and compare it with the delorian-based code:

from delorean import Delorean

EST = "US/Eastern"

d = Delorean(timezone=EST)

我相信 datetime 示例应该写成:

from datetime import datetime
import pytz

eastern_timezone = pytz.timezone("US/Eastern")
d = datetime.now(eastern_timezone)

更简洁。

有没有最后一个代码示例失败,而第一个继续工作?

Are there any cases when the last code example fails while the first one continues to work?

更新: 当前示例:

from datetime import datetime
import pytz

d = datetime.utcnow()
d = pytz.utc.localize(d)

est = pytz.timezone('US/Eastern')
d = est.normalize(d)
return d

仍然太冗长。

问题仍然如下:你需要通过utc和 tz.normalize()的显式往返,或者可以使用 datetime.now(tz)

The question stills stands: do you need the explicit round-trip via utc and tz.normalize() or can you use datetime.now(tz) instead?

推荐答案


什么时候 datetime.now(pytz_timezone )失败?

据我所知,没有可能会失败的场景。 datetime.now tzinfo 实例中调用 fromutc 函数传入参数。从UTC到本地时间的所有转换都是明确的,所以没有失败的机会。

As far as I can tell, there are no scenarios where it could fail. datetime.now invokes the fromutc function on the tzinfo instance passed in the parameter. All conversions from UTC to local time are unambiguous, so there are no opportunities for failure.

此外,原始代码甚至不起作用。

Also, the original code does not even work.

d = est.normalize(EST)

这似乎传递一个字符串作为 normalize 的唯一参数,该参数旨在使 datetime 。这给出了:

This would appear to pass a string as the only parameter to normalize, which is intended to take a datetime. This gives:

AttributeError: 'str' object has no attribute 'tzinfo'

我相信他们打算写:

d = est.normalize(d.astimezone(est))

说,我不认为他们的代码的冗长度增加了很多价值。正如你所说,在一个单一的步骤中,这样做很简单:

That said, I don't think the verbosity of their code adds much value. As you noted, it's just as easy to do this in a single step:

d = datetime.now(est)

查看 cpython源代码 datetime.now ,我可以看到,当一个 tzinfo 对象,它调用该对象的 fromutc 方法。

Looking at the cpython source code for datetime.now, I can see that when a tzinfo object is provided, it calls the fromutc method on that object.

if (self != NULL && tz != Py_None) {
    /* Convert UTC to tzinfo's zone. */
    PyObject *temp = self;

    self = _PyObject_CallMethodId(tz, &PyId_fromutc, "O", self);
    Py_DECREF(temp);
}

然后,在pytz源中,我看到 fromutc 方法根据区域是否为 pytz.UTC StaticTzInfo DstTzInfo 。在所有三种情况下,从输入的UTC值到目标时区的转换是明确的。这里是 DstTzInfo 实现,这是更复杂的三个:

Then, in the pytz source, I see that the fromutc method is implemented differently depending on whether the zone is pytz.UTC, or an instance of StaticTzInfo, or DstTzInfo. In all three cases, the transformation from the input UTC value to the target time zone is unambiguous. Here is the DstTzInfo implementation, which is the more complex of the three:

def fromutc(self, dt):
    '''See datetime.tzinfo.fromutc'''
    if (dt.tzinfo is not None
        and getattr(dt.tzinfo, '_tzinfos', None) is not self._tzinfos):
        raise ValueError('fromutc: dt.tzinfo is not self')
    dt = dt.replace(tzinfo=None)
    idx = max(0, bisect_right(self._utc_transition_times, dt) - 1)
    inf = self._transition_info[idx]
    return (dt + inf[0]).replace(tzinfo=self._tzinfos[inf])

这似乎是从 _utc_transition_times 的时区,然后将其应用于返回的 datetime 。这个方向没有歧义,所以结果将是等同的。

This would appear to find the transition from _utc_transition_times of the time zone, then apply it to the returned datetime. There are no ambiguities in this direction, so the results will be equivalent.

另外值得一提的是,在 datetime docs ,它表示 datetime.now 相当于调用:

Also worth noting, in the datetime docs it says that datetime.now is equivalent to calling:

tz.fromutc(datetime.utcnow().replace(tzinfo=tz))

鉴于 fromutc的来源在pyts中我显示较早,我不知道这是有什么不同的:

Given the source of fromutc in pytz I showed earlier, I'm not sure that this is any different than just:

tz.fromutc(datetime.utcnow())

但是无论如何,我不认为 localize 正常化是必要的。

But in either case, I don't think localize and normalize are necessary.

这篇关于`datetime.now(pytz_timezone)'何时失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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