Difference between revisions of "Using Python datetime with Timezones"
Jump to navigation
Jump to search
PeterHarding (talk | contribs) |
PeterHarding (talk | contribs) |
||
| Line 12: | Line 12: | ||
# This is a naive datetime value | # This is a naive datetime value | ||
print(dt.isoformat()) | print(f" TZ naive datetime value |{dt.isoformat()}|") | ||
print(dt.tzinfo) | print(f" dt.tzinfo |{dt.tzinfo}|") | ||
# Cast this as UTC | # Cast this as UTC | ||
| Line 27: | Line 27: | ||
tz_aware_dt = dt.astimezone(datetime.strptime(offset, "%z").tzinfo) | tz_aware_dt = dt.astimezone(datetime.strptime(offset, "%z").tzinfo) | ||
print(tz_aware_dt.isoformat()) | print(f" TZ Aware dt |{tz_aware_dt.isoformat()}|") | ||
</pre> | </pre> | ||
Revision as of 10:23, 5 June 2022
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()}|")