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
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.