如何在python中将时区添加到天真的日期时间实例中

如何在python中将时区添加到天真的日期时间实例中

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

问题描述

我有一个没有时区信息的 datetime.我现在正在获取时区信息并想将时区添加到现有的日期时间实例中,我该怎么做?

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

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

How to add the timezone info tz into datetime a

推荐答案

使用 tz.localize(d) 对实例进行本地化.来自文档:

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

首先是使用pytz库提供的localize()方法.这用于本地化一个简单的日期时间(没有时区信息的日期时间):

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

如果您使用tz.localize(),但使用datetime.replace(),那么historical 使用偏移量代替;tz.localize() 将选择对给定日期有效的正确偏移量.例如,美国东部时区 DST 的开始和结束日期随时间而变化.

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.

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

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)

甚至通过设置 is_dst=None 完全关闭选择.在这种情况下,或者在极少数情况下, 没有为时区设置默认值,不明确的日期时间值将导致引发 AmbiguousTimeError 异常.is_dst 标志仅用于不明确的日期时间值,否则将被忽略.

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.

要返回另一种方式,将时区感知对象变回原始对象,请使用 .replace(tzinfo=None):

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中将时区添加到天真的日期时间实例中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-27 23:05