Create date-and-time values and distinguish naive from aware objects.
How It Works
datetime.datetime holds date and time together; timezone-aware values include tzinfo and can represent instants consistently. Comparing naive and aware values with ordering operators raises TypeError.
Step-by-Step Example
from datetime import datetime, timezone
meeting_time = datetime(2026, 10, 17, 14, 15, tzinfo=timezone.utc)
print(meeting_time.isoformat())
print(meeting_time.year, meeting_time.hour)
Understanding the Example
- The expression 'datetime(2026, 10, 17, 14, 15, tzinfo=timezone.utc)' supplies the value stored as 'meeting_time'. This value is then used or checked by the later statements.
- The print() call exposes the result so you can compare it with the behavior described above. Check the value and its type when experimenting.
A successful run of this example prints the following output:
2026-10-17T14:15:00+00:00
2026 14
Where This Fits in a Real Program
For event timestamps, distinguish the displayed local clock from the instant that it represents. Store or exchange an unambiguous aware value, then convert it when displaying it to a user. For repeated calendar appointments, use a geographic timezone so daylight-saving rules are not lost.
Practice: Try It Yourself
Prefer aware UTC values for storage and UTC-to-local conversion at display time.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Attaching a timezone label without converting the underlying instant, or comparing naive and aware values.
- Represent a meeting at 14:15 UTC and convert it to another time zone.
Key Takeaways
- Create date-and-time values and distinguish naive from aware objects.
- datetime.datetime holds date and time together; timezone-aware values include tzinfo and can represent instants consistently.
- Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.