Format a struct_time or current local time with time.strftime().
How It Works
time.strftime(format, tuple) converts time components into a string using directives such as %Y, %m, and %d. Without a tuple, the local current time is used, which can make example outputs non-reproducible.
Step-by-Step Example
import time
utc_components = time.gmtime(0)
print(time.strftime('%Y-%m-%d', utc_components))
Understanding the Example
- The expression 'time.gmtime(0)' supplies the value stored as 'utc_components'. 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:
1970-01-01
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 datetime.strftime() for timezone-aware date-time objects.
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 month %m with minute %M or assuming a locale-dependent format is fixed everywhere.
- Format a supplied UTC struct_time as a year/month/day string.
Key Takeaways
- Format a struct_time or current local time with time.strftime().
- time.strftime(format, tuple) converts time components into a string using directives such as %Y, %m, and %d.
- Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.