Last active
March 28, 2020 01:34
-
-
Save krystofl/15949046551e778b21fd6bf69f8885b1 to your computer and use it in GitHub Desktop.
Some sample code showing how to use the python timezone library - pytz
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
#!/usr/bin/python3 | |
''' | |
Tests to learn how to use the pytz timezone library properly | |
http://pytz.sourceforge.net | |
''' | |
import os | |
import sys | |
import datetime | |
import pytz | |
# Krystof utils | |
KRYSTOF_UTILS_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), | |
'krystof-utils', 'python') | |
sys.path.append(KRYSTOF_UTILS_PATH) | |
from krystof_utils import MSG, TODO | |
TIME_FORMAT = '%Y-%m-%d %H:%M:%S %Z%z' | |
def get_tz_offset_from_utc_str(tz_name, dt): | |
''' | |
get the offset between the timezone named tz_name and UTC on at datetime dt | |
dt is a datetime.datetime | |
returns a string like "-06" | |
''' | |
# uses noon to be avoid any weirdness around the start and end of DST | |
tz = pytz.timezone(tz_name) | |
localtime = tz.localize(dt) | |
offset = localtime.strftime('%z') | |
MSG("localtime: {}".format(localtime.strftime(TIME_FORMAT))) | |
MSG("offset : {}".format(offset)) | |
return offset | |
if __name__ == '__main__': | |
MSG("pytz version: {}".format(pytz.__version__)) | |
MSG("US time zones: {}".format(', '.join(pytz.country_timezones('US')))) | |
# CA timezone | |
catz = pytz.timezone('America/Los_Angeles') | |
# A date when daylight saving time is NOT in effect | |
LA_winter = catz.localize(datetime.datetime(2019, 1, 8, 0, 0)) | |
MSG("LA time (WINTER): {}".format(LA_winter.strftime(TIME_FORMAT))) | |
# A date when DST IS in effect | |
LA_summer = catz.localize(datetime.datetime(2019, 8, 8, 0, 0)) | |
MSG("LA time (summer): {}".format(LA_summer.strftime(TIME_FORMAT))) | |
offset = get_tz_offset_from_utc_str('America/Los_Angeles', | |
datetime.datetime(2019, 8, 8, 0, 0)) | |
MSG('summer offset: {}'.format(offset)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment