Created
November 17, 2019 14:24
-
-
Save karpanGit/c04d19f391c37f001e63794ff08dfaad to your computer and use it in GitHub Desktop.
timezones in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# working with timezones | |
from datetime import datetime | |
# pytz is required for timezone aware datetime and time objects | |
import pytz | |
# help function | |
def checkAwareness(dt): | |
if dt.tzinfo is None: | |
print(f'datetime is naive (tzinfo is {dt.tzinfo})') | |
else: | |
print(f'datetime is aware (tzinfo is {dt.tzinfo})') | |
# obtain the current time (it is naive, i.e. it is not timezone aware) | |
now = datetime.now() | |
print(f'now time is {now}') | |
checkAwareness(now) | |
# example 1: make datetime object timezone aware | |
timezone = pytz.timezone('Europe/Helsinki') | |
now_aware = timezone.localize(now) | |
print(f'now aware time is {now_aware}') | |
checkAwareness(now_aware) | |
# example 2: best practice: | |
# - use aware datetime objects | |
# - work with UTC time and convert to desired timezone at the end | |
now_utc = datetime.utcnow() | |
print(f'UTC time is {now_utc}') | |
checkAwareness(now_utc) | |
# set the timezone as UTC | |
timezone = pytz.timezone('UTC') | |
now_utc_aware = timezone.localize(now_utc) | |
print(f'UTC aware time is {now_utc_aware}') | |
checkAwareness(now_utc_aware) | |
# obtain the time in Helsinki | |
now_Helsinki_aware = now_utc_aware.astimezone(pytz.timezone('Europe/Helsinki')) | |
print(f'Helsinki aware time is {now_Helsinki_aware}') | |
checkAwareness(now_Helsinki_aware) | |
# output | |
# now time is 2019-11-17 16:23:43.040856 | |
# datetime is naive (tzinfo is None) | |
# now aware time is 2019-11-17 16:23:43.040856+02:00 | |
# datetime is aware (tzinfo is Europe/Helsinki) | |
# UTC time is 2019-11-17 14:23:43.040856 | |
# datetime is naive (tzinfo is None) | |
# UTC aware time is 2019-11-17 14:23:43.040856+00:00 | |
# datetime is aware (tzinfo is UTC) | |
# Helsinki aware time is 2019-11-17 16:23:43.040856+02:00 | |
# datetime is aware (tzinfo is Europe/Helsinki) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment