Using Python datetime with Timezones

From PeformIQ Upgrade
Revision as of 09:23, 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(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"

# Convert as so...

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

print(f" TZ Aware dt |{tz_aware_dt.isoformat()}|")