Choose timezone-aware datetimes over ambiguous naive timestamps.
How It Works
A naive datetime has tzinfo=None and does not say what time zone its clock fields represent. An aware datetime has offset-related information, allowing more reliable conversion and comparison of real instants.
Step-by-Step Example
from datetime import datetime, timezone
naive_time = datetime(2026, 10, 17, 10)
aware_time = datetime(2026, 10, 17, 10, tzinfo=timezone.utc)
print(naive_time.tzinfo is None)
print(aware_time.tzinfo is not None)
Understanding the Example
- The expression 'datetime(2026, 10, 17, 10)' supplies the value stored as 'naive_time'. This value is then used or checked by the later statements.
- The expression 'datetime(2026, 10, 17, 10, tzinfo=timezone.utc)' supplies the value stored as 'aware_time'. This value is then used or checked by the later statements.
A successful run of this example prints the following output:
True
True
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
Define the meaning of legacy naive timestamps before attaching an offset.
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
- Mixing timezone-aware and naive datetimes in ordering comparisons or treating every naive timestamp as UTC.
- Convert an existing UTC source into aware datetimes before storing it.
Key Takeaways
- Choose timezone-aware datetimes over ambiguous naive timestamps.
- A naive datetime has tzinfo=None and does not say what time zone its clock fields represent.
- Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.