Using Python datetime with Timezones

From PeformIQ Upgrade
Revision as of 10:18, 5 June 2022 by PeterHarding (talk | contribs) (Created page with " =Explicit Numerical Offsets from UTC= <pre> 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()) </pre> Category:Python Category:datetime Category:EXamples")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Explicit Numerical Offsets from UTC

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())