Parse fixed-format date-time strings with time.strptime().
How It Works
time.strptime(text, format) produces a struct_time based on the supplied directives. It does not automatically attach a named timezone or resolve daylight-saving ambiguity.
Step-by-Step Example
import time
parsed_components = time.strptime('2026-10-17 15:40', '%Y-%m-%d %H:%M')
print(parsed_components.tm_year)
print(parsed_components.tm_hour)
Understanding the Example
- The expression "time.strptime('2026-10-17 15:40', '%Y-%m-%d %H:%M')" supplies the value stored as 'parsed_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:
2026
15
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.strptime() when you need a datetime object for arithmetic.
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
- Using a mismatched directive such as %m for minutes or assuming the result is an aware datetime.
- Parse a fixed log timestamp and read its tm_wday field.
Key Takeaways
- Parse fixed-format date-time strings with time.strptime().
- time.strptime(text, format) produces a struct_time based on the supplied directives.
- Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.