如何在python中将时区添加到一个简单的日期时间实例中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13994594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add timezone into a naive datetime instance in python
提问by waitingkuo
I've got a datetimewhich 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?
我有一个datetime没有时区信息的。我现在正在获取时区信息并想将时区添加到现有的日期时间实例中,我该怎么办?
d = datetime.datetime.now()
tz = pytz.timezone('Asia/Taipei')
How to add the timezone info tzinto datetime a
如何将时区信息添加tz到日期时间a
采纳答案by Martijn Pieters
Use tz.localize(d)to localize the instance. From the documentation:
使用tz.localize(d)本地化的实例。从文档:
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
首先是使用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
If you don'tuse tz.localize(), but use datetime.replace(), chances are that a historicaloffset 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.
如果您不使用tz.localize(),而是使用datetime.replace(),则可能会使用历史偏移量;tz.localize()将选择对给定日期有效的正确偏移量。例如,美国东部时区 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_dstkeyword argument for .localize():
当您尝试本地化一个不明确的日期时间值时,因为它跨越了从夏令时到冬令时的过渡期,反之亦然,将咨询时区以查看生成的日期时间对象是否应该.dst()返回 True 或 False。您可以使用以下is_dst关键字参数覆盖时区的默认值.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 isno default set for a timezone, an ambiguous datetime value would lead to a AmbiguousTimeErrorexception being raised. The is_dstflag is only consulted for datetime values that are ambiguous and is ignored otherwise.
甚至通过设置完全关闭选择is_dst=None。在这种情况下,或在极少数情况下有是没有默认的时区设置,不明确的日期时间值会导致AmbiguousTimeError被引发的异常。该is_dst标志仅用于不明确的日期时间值,否则将被忽略。
To go back the other way, turn a timezone-aware object back to a naive object, use .replace(tzinfo=None):
要以另一种方式返回,请将时区感知对象变回幼稚对象,请使用.replace(tzinfo=None):
naivedt = awaredt.replace(tzinfo=None)
回答by hobs
If you know that your original datetime was "measured" in the time zone you are trying to add to it, you could (but probably shouldn't) use replacerather than localize.
如果您知道您的原始日期时间是在您尝试添加的时区中“测量”的,您可以(但可能不应该)使用replace而不是localize.
# d = datetime.datetime.now()
# tz = pytz.timezone('Asia/Taipei')
d = d.replace(tzinfo=tz)
I can imagine 2 times when this might make sense (the second one happened to me):
我可以想象两次这可能有意义(第二次发生在我身上):
- Your server locale is set to the incorrect time zone and you are trying to correct a
datetimeinstance by making it aware of this incorrect timezone (and presumably later localizing it to the "correct" time zone so the values of now() match up to other times you are comparing it to (your watch, perhaps) - You want to "tag" a
timeinstance (NOTadatetime) with a time zone (tzinfo) attribute so that attribute can be used later to form a fulldatetimeinstance.
- 您的服务器区域设置设置为不正确的时区,并且您正试图
datetime通过使其意识到此不正确的时区来更正实例(并且可能稍后将其本地化为“正确”时区,以便 now() 的值与其他时区匹配您将其与(可能是您的手表)进行比较的次数 - 您想用时区 (tzinfo) 属性“标记”一个
time实例(不是adatetime),以便稍后可以使用该属性来形成完整的datetime实例。

