Environment: Python-3.5
Python time is created with the time zone in mind. A note about how to handle time zones. The timezone-naive is the time when the timezone is not conscious, and the timezone-aware is the time when the timezone is conscious.
from datetime import datetime,timezone
import pytz
naive = datetime.now()
aware = datetime.now(timezone.utc)
Passing timezone
as an argument to timezone # now
creates a timezone-aware current time.
The two cannot be compared.
naive > awre
# TypeError: can't compare offset-naive and offset-aware datetimes
An exception is thrown.
When creating an arbitrary time, pass the timezone as an argument as follows.
naive = datetime(2016,6,1,12,0,0,0)
aware = datetime(2016,6,1,12,0,0,0,timezone.utc)
Use datetime # astimezone
if you want to change to your local timezone.
Of course, time zone-naive time cannot be used.
print(naive.astimezone())
# ValueError: astimezone() cannot be applied to a naive datetime
print(aware.astimezone())
# 2016-06-01 21:00:00+09:00
It is convenient to use pytz
when using your favorite time zone.
timezone-Changes a naive time to the specified timezone.
import pytz
de = pytz.timezone('Europe/Berlin')
print(de.localize(naive))
# 2016-06-01 12:00:00+02:00
jp = pytz.timezone('Asia/Tokyo')
print(jp.localize(naive))
# 2016-06-01 12:00:00+09:00
timezone-Change the time zone of aware time. This does not change the actual time.
print(aware.astimezone(jp))
# 2016-06-01 21:00:00+09:00
print(aware.astimezone(de))
# 2016-06-01 14:00:00+02:00
You can override the timezone with datetime # replace
. Naturally, the time to express will change.
print(aware.replace(tzinfo=jp).astimezone(timezone.utc))
# 2016-06-01 03:00:00+00:00
print(aware.replace(tzinfo=de).astimezone(timezone.utc))
# 2016-06-01 11:07:00+00:00
Recommended Posts