Exercise #1
Create a variable named moscow that holds a datetime.timezone object at +4 hours.
Then create a timezone variable named pacific that holds a timezone at UTC-08:00.
Finally, make a third variable named india that hold’s a timezone at UTC+05:30.
import datetime moscow = datetime.timezone(datetime.timedelta(hours=4)) pacific = datetime.timezone(datetime.timedelta(hours=-8)) india = datetime.timezone(datetime.timedelta(hours=5, minutes=30))
Exercise #2
naive is a datetime with no timezone.
Create a new timezone for US/Pacific, which is 8 hours behind UTC (UTC-08:00).
Then make a new variable named hill_valley that is naive with its tzinfo attribute replaced with the US/Pacific timezone you made.
import datetime naive = datetime.datetime(2015, 10, 21, 4, 29) pacific = datetime.timezone(datetime.timedelta(hours=-8)) hill_valley = naive.replace(2015, 10, 21, 4, 29, tzinfo=pacific) Great, but replace just sets the timezone, it doesn't move the datetime to the new timezone. Let's move one. Make a new timezone that is UTC+01:00. Create a new variable named paris that uses your new timezone and the astimezone method to change hill_valley to the new timezone. newtz = datetime.timezone(datetime.timedelta(hours=1)) paris = hill_valley.astimezone(newtz)
Exercise #3
starter is a naive datetime. Use pytz to make it a “US/Pacific” datetime instead and assign this converted datetime to the variable local. Then create a variable named pytz_string by using strftime with the local datetime. Use the fmt string for the formatting.
import datetime import pytz fmt = '%m-%d %H:%M %Z%z' starter = datetime.datetime(2015, 10, 21, 4, 29) pacific = pytz.timezone('US/Pacific') local = pacific.localize(starter) pytz_string = local.strftime(fmt)
Exercise: Meeting App
We’re building a script that takes a date and time, and then gives it back to us in six other time zones.
You’d use it to figure out what time your meetings are in other time zones for all of your intercontinental business meetings. So we have two hard steps, turning our datetime into UTC, and then making our six other datetimes.
from datetime import datetime import pytz OTHER_TIMEZONES = [ pytz.timezone('US/Eastern'), pytz.timezone('Pacific/Auckland'), pytz.timezone('Asia/Calcutta'), pytz.timezone('UTC'), pytz.timezone('Europe/Paris'), pytz.timezone('Africa/Khartoum') ] fmt = '%Y-%m-%d %H:%M:%S %Z%z' while True: date_input = input("When is your meeting? Please use MM/DD/YYYY HH:MM format. ") try: local_date = datetime.strptime(date_input, '%m/%d/%Y %H:%M') except ValueError: print("{} doesn't seem to be a valid date & time.".format(date_input)) else: local_date = pytz.timezone('US/Pacific').localize(local_date) utc_date = local_date.astimezone(pytz.utc) output = [] for timezone in OTHER_TIMEZONES: output.append(utc_date.astimezone(timezone)) for appointment in output: print(appointment.strftime(fmt)) break