from datetime import date
dt = date.fromisoformat(date.today().strftime('%Y-%m-%d'))
print(dt)
Output
2019-09-17
By using date string
from datetime import date
dt = date.fromisoformat('2019-09-22')
print(dt)
Output is here
2019-09-22
Handling Invalid Date Strings:
from datetime import date
try:
dt = date.fromisoformat('2019-02-30') # Invalid date
except ValueError as e:
print(f"Error: {e}")
Output
Error: day is out of range for month
fromisoformat(): A simple, direct method to parse ISO date strings in the YYYY-MM-DD format. It's faster and requires no format specification.
strptime(): More versatile but requires a format string to define the structure of the input. It’s useful for parsing dates in various formats.
from datetime import date, datetime
# Using fromisoformat
print(date.fromisoformat('2023-09-12'))
# Using strptime for the same result
print(datetime.strptime('2023-09-12', '%Y-%m-%d').date())
Output
2023-09-12
2023-09-12
fromisoformat() is simpler when handling standard ISO dates, while strptime() is needed for more complex formats.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.