Get the current date and time with appropriate timezone awareness.
How It Works
datetime.now(tz=timezone.utc) returns an aware UTC datetime, while now() without tz returns a naive local datetime. The returned instant changes between calls, so tests should inject a fixed clock or compare ranges rather than exact text.
Step-by-Step Example
from datetime import datetime, timezone
current_time = datetime.now(timezone.utc)
print(current_time.tzinfo is not None)
print(current_time.utcoffset().total_seconds() == 0)
Understanding the Example
- The expression 'datetime.now(timezone.utc)' supplies the value stored as 'current_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:
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
Store UTC where possible and translate to local display formats only when needed.
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
- Assuming datetime.now() always returns UTC or comparing a changing current time to one hardcoded value.
- Display an aware UTC timestamp in ISO 8601 format.
Key Takeaways
- Get the current date and time with appropriate timezone awareness.
- datetime.now(tz=timezone.utc) returns an aware UTC datetime, while now() without tz returns a naive local datetime.
- Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.