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:If you don’t use
tz.localize(), but usedatetime.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 theis_dstkeyword argument for.localize():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 aAmbiguousTimeErrorexception being raised. Theis_dstflag 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):