Format datetime values as readable text with strftime directives.
How It Works
datetime.strftime(format) renders components using tokens such as %Y for a four-digit year and %H for 24-hour time. Formatting changes representation, not the stored instant or its timezone.
Step-by-Step Example
from datetime import datetime, timezone
recorded_time = datetime(2026, 10, 17, 9, 5, tzinfo=timezone.utc)
print(recorded_time.strftime('%d/%m/%Y %H:%M UTC'))
Understanding the Example
- The expression 'datetime(2026, 10, 17, 9, 5, tzinfo=timezone.utc)' supplies the value stored as 'recorded_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:
17/10/2026 09:05 UTC
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
Use strptime() for reverse parsing when the format is known.
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
- Confusing %m (month) with %M (minute), or believing formatted text keeps timezone metadata.
- Create both an ISO date and a friendly display label from the same datetime.
Key Takeaways
- Format datetime values as readable text with strftime directives.
- datetime.strftime(format) renders components using tokens such as %Y for a four-digit year and %H for 24-hour time.
- Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.