Using Python datetime with Timezones

From PeformIQ Upgrade
Revision as of 19:31, 5 June 2022 by PeterHarding (talk | contribs)
Jump to navigation Jump to search

Binding with Timezone Info

cat !$
cat ./py_tz_example_01.py
#!/usr/bin/env python3

import pytz 

from datetime import datetime 

def list_tz():
    for tz in pytz.all_timezones:
        print(tz)


def example(tz_name):

    specified_tz = pytz.timezone(tz_name)

    # transform to a time using a specific timezone 

    tz_aware_dt = datetime.now(tz=specified_tz)

    print(f"TZ aware datetime value |{tz_aware_dt.isoformat()}| for timezone - '{tz_name}'")


# list_tz()

print(f"TZ naive datetime value |{datetime.now().isoformat()}|")

example("America/New_York")
example("America/Vancouver")
example("Asia/Tokyo")
example("Australia/Sydney")
example("Europe/London")
example("Europe/Paris")


% ./py_tz_example_01.py    
TZ naive datetime value |2022-06-05T09:48:41.237251|
TZ aware datetime value |2022-06-04T19:48:41.249310-04:00| for timezone - 'America/New_York'
TZ aware datetime value |2022-06-04T16:48:41.249630-07:00| for timezone - 'America/Vancouver'
TZ aware datetime value |2022-06-05T08:48:41.249701+09:00| for timezone - 'Asia/Tokyo'
TZ aware datetime value |2022-06-05T09:48:41.249923+10:00| for timezone - 'Australia/Sydney'
TZ aware datetime value |2022-06-05T00:48:41.250303+01:00| for timezone - 'Europe/London'
TZ aware datetime value |2022-06-05T01:48:41.250543+02:00| for timezone - 'Europe/Paris'


Explicit Numerical Offsets from UTC

#!/usr/bin/env python3

from datetime import datetime, timezone

dt = datetime.now()

# This is a naive datetime value

print(f" TZ naive datetime value |{dt.isoformat()}|")
print(f"               dt.tzinfo |{dt.tzinfo}|")

# Cast this as UTC

dt = dt.replace(tzinfo=timezone.utc)

# Define the offset

offset = "+1000"  # "Australia/Melbourne"

# Convert as so...

tz_aware_dt = dt.astimezone(datetime.strptime(offset, "%z").tzinfo)

print(f" TZ Aware datetime value |{tz_aware_dt.isoformat()}|")
% ./py_tz_example_02.py
 TZ naive datetime value |2022-06-05T09:49:37.782118|
               dt.tzinfo |None|
 TZ Aware datetime value |2022-06-05T19:49:37.782118+10:00|