Parse strings using an explicit date-time format.
How It Works
datetime.strptime(text, format) uses directives such as %Y, %m, and %d. Inputs must match the expected layout, and missing year information can cause leap-day ambiguity; prefer complete four-digit years.
Step-by-Step Example
from datetime import datetime
parsed_date = datetime.strptime('17/10/2026 09:15', '%d/%m/%Y %H:%M')
print(parsed_date.isoformat())
Understanding the Example
- The expression "datetime.strptime('17/10/2026 09:15', '%d/%m/%Y %H:%M')" supplies the value stored as 'parsed_date'. 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-10-17T09:15:00
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
For an ISO 8601 timestamp, fromisoformat() is often simpler.
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
- Mixing up month and day directives or assuming parsing adds timezone information automatically.
- Parse an event date written as 2026-10-17 09:15 with an explicit format.
Key Takeaways
- Parse strings using an explicit date-time format.
- datetime.strptime(text, format) uses 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.