Working with dates and times often starts with converting strings into proper Python objects. Traditionally, Python developers relied on datetime.strptime for this task, even when they only needed a date or time object. Since Python 3.14, dates and times can be parsed directly, without extra steps.
Before Python 3.14, parsing a date-only or time-only string required using the datetime class and then extracting the needed component. This approach worked, but it introduced unnecessary boilerplate.
from datetime import datetime
dt = datetime.strptime('2026-01-02', '%Y-%m-%d').date()
print(type(dt)) # <class 'datetime.date'>
tm = datetime.strptime('08:50:30', '%H:%M:%S').time()
print(type(tm)) # <class 'datetime.time'>
Also, this method forced developers to create a full datetime object, even when only a date or time was required.
Since Python 3.14, the strptime method is added directly to the date and time classes. This means strings can now be parsed straight into the desired type, without passing through datetime.
from datetime import date
from datetime import time
dt = date.strptime('2026-01-02', '%Y-%m-%d')
print(type(dt)) # <class 'datetime.date'>
tm = time.strptime('08:50:30', '%H:%M:%S')
print(type(tm)) # <class 'datetime.time'>
The formatting rules remain the same as those used by datetime.strptime, so existing format strings continue to work without modification.
Leave a Comment
Cancel reply