如何在python中将时区添加到一个简单的日期时间实例中 [英] How to add timezone into a naive datetime instance in python

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

问题描述

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

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

如何将时区信息tz添加到日期时间a

解决方案

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

<块引用>

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

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

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

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

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

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

反过来,将时区感知对象变回原始对象,使用.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中将时区添加到一个简单的日期时间实例中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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