Sub topic 2
Getting the Current Time and Working with Timestamps
Assume you know basic Python imports, functions, and exceptions, and understand UTC and offsets. This chapter uses Python 3.9 or later.
Getting the current time and working with timestamps
Use an aware datetime for the current time. An aware datetime includes time-zone information.
from datetime import datetime, timezone
now = datetime.now(timezone.utc)
timestamp = now.timestamp()
restored = datetime.fromtimestamp(timestamp, tz=timezone.utc)
print(now)
print(timestamp)
print(restored == now)A POSIX timestamp is a number of seconds since 1970-01-01 00:00:00 UTC. It is useful for storage and comparison, but it does not preserve the original time zone. Convert it back with the intended zone.
Parsing and formatting
ISO 8601 is a standard text format for dates and times. Use fromisoformat() when the input follows that format. Use strptime() for a custom layout and strftime() to produce formatted text.
from datetime import datetime
dt = datetime.fromisoformat("2026-11-26T11:07:59+00:00")
print(dt.isoformat())
parsed = datetime.strptime("26/11/2026 11:07", "%d/%m/%Y %H:%M")
print(parsed.strftime("%A, %d %B %Y"))Common format codes include %Y for a four-digit year, %m for a month, %d for a day, %H for a 24-hour hour, and %M for minutes.
Real-world time zones with `ZoneInfo`
ZoneInfo uses IANA time-zone data, such as America/New_York or Asia/Tokyo. It accounts for historical offset changes and daylight saving time.
from datetime import datetime
from zoneinfo import ZoneInfo
meeting = datetime(
2026, 11, 26, 9, 0,
tzinfo=ZoneInfo("America/New_York")
)
print(meeting)Converting between time zones
Use astimezone() to represent the same instant in another zone.
from datetime import timezone
print(meeting.astimezone(timezone.utc))
print(meeting.astimezone(ZoneInfo("Asia/Tokyo")))If time-zone data is unavailable on the operating system, install the tzdata package so ZoneInfo can find the IANA database.
Exercise
Which method converts an aware datetime to another time zone?
Show answer
Call astimezone() with a ZoneInfo object or another timezone object.