Replace deprecated utcnow() usage with timezone-aware UTC datetimes.
How It Works
datetime.utcnow() returns a naive datetime and has been deprecated since Python 3.12. Use datetime.now(timezone.utc) so the UTC offset is explicit, reducing the chance that another API will treat the value as local time.
Step-by-Step Example
from datetime import datetime, timezone
created_at = datetime.now(timezone.utc)
print(created_at.tzinfo == timezone.utc)
print(created_at.isoformat().endswith('+00:00'))
Understanding the Example
- The expression 'datetime.now(timezone.utc)' supplies the value stored as 'created_at'. 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:
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
Do not simply replace tzinfo on an arbitrary local datetime to convert it to UTC.
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
- Calling utcnow() and assuming its timezone information is attached automatically.
- Refactor a log timestamp from utcnow() to now(timezone.utc).
Key Takeaways
- Replace deprecated utcnow() usage with timezone-aware UTC datetimes.
- datetime.utcnow() returns a naive datetime and has been deprecated since Python 3.12.
- Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.