如何将时区添加到python中的一个天真的datetime实例中 [英] How to add timezone into a naive datetime instance in python

查看:142
本文介绍了如何将时区添加到python中的一个天真的datetime实例中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 datetime ,没有时区信息。我现在正在获取时区信息,并希望将时区添加到现有的datetime实例中,我该怎么办?

  d = datetime.datetime.now()
tz = pytz.timezone('亚洲/台北')

如何将时区信息 tz 添加到datetime a

解决方案

使用 tz.localize(d)来本地化实例。从文档


第一个是使用由pytz库提供的localize()方法。这用于本地化一个天真的datetime(没有时区信息的datetime):

 >>> loc_dt = east.localize(datetime(2002,10,27,6,0,0))
>>>打印(loc_dt.strftime(fmt))
2002-10-27 06:00:00 EST-0500


< blockquote>

如果您不要使用 tz.localize(),但使用 datetime.replace(),可能会使用历史偏移; tz.localize()将为给定日期选择正确的偏移量。美国东部时区DST的开始和结束日期已经随着时间的推移而变化。



当您尝试本地化一个含义不明的datetime值,因为它跨越了过渡期夏季至冬季或反之亦然,将查询时区以查看生成的日期时间对象是否应具有 .dst()返回True或False。您可以使用 is_dst 关键字参数为 .localize()

$覆盖时区的默认值: b
$ b

  dt = tz.localize(naive,is_dst = True)

甚至通过设置 is_dst = None 完全关闭选项。在这种情况下,或者在极少数情况下,没有为时区设置默认值,不明确的datetime值会导致引发 AmbiguousTimeError 异常。



要追溯到另一​​个方面,使用 .replace(tzinfo = None)

  naivedt = awaredt.replace(tzinfo = None)


I've got a datetime which has no timezone information. I'm now getting the timezone info and would like to add the timezone into the existed datetime instance, how can I do?

d = datetime.datetime.now()
tz = pytz.timezone('Asia/Taipei')

How to add the timezone info tz into datetime a

解决方案

Use tz.localize(d) to localize the instance. From the documentation:

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):

>>> loc_dt = eastern.localize(datetime(2002, 10, 27, 6, 0, 0))
>>> print(loc_dt.strftime(fmt))
2002-10-27 06:00:00 EST-0500

If you don't use tz.localize(), but use datetime.replace(), chances are that a historical offset is used instead; tz.localize() will pick the right offset in effect for the given date. The US Eastern timezone DST start and end dates have changed over time, for example.

When you try to localize a datetime value that is ambiguous because it straddles the transition period from summer to winter time or vice-versa, the timezone will be consulted to see if the resulting datetime object should have .dst() return True or False. You can override the default for the timezone with the is_dst keyword argument for .localize():

dt = tz.localize(naive, is_dst=True)

or even switch off the choice altogether by setting is_dst=None. In that case, or in the rare cases there is no default set for a timezone, an ambiguous datetime value would lead to a AmbiguousTimeError exception being raised. The is_dst flag is only consulted for datetime values that are ambiguous and is ignored otherwise.

To go back the other way, turn a timezone-aware object back to a naive object, use .replace(tzinfo=None):

naivedt = awaredt.replace(tzinfo=None)

这篇关于如何将时区添加到python中的一个天真的datetime实例中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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