Using Python datetime with Timezones

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

Explicit Numerical Offsets from UTC

#!/usr/bin/env python3

from datetime import datetime, timezone

dt = datetime.now()

# This is a naive datetime value

print(dt.isoformat())
print(dt.tzinfo)

# Cast this as UTC

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

# Define the offset

offset = "+1000"

# Convert as so...

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

print(tz_aware_dt.isoformat())