date.fromisoformat() converts a supported ISO 8601 date string into a Python datetime.date object. A common input is YYYY-MM-DD, such as 2019-09-22. Once parsed, the date can be compared, sorted, and used in calculations.
Start with this runnable example (available in Python 3.7 and later):
from datetime import date
dt = date.fromisoformat('2019-09-22')
print(dt)
Output:
2019-09-22
The string 2019-09-22 becomes a datetime.date object. Printing that object uses the familiar YYYY-MM-DD representation. This preserves the original tutorial’s fixed-date demonstration.
Run the examples, try invalid dates, compare strptime() and test your answers with guided exercises.
Uses the Python standard library. Publish the notebook to GitHub before deploying these links.
Use date.fromisoformat(date_string). The required argument is a string representing a supported ISO 8601 date. In Python 3.7–3.10, the supported format was YYYY-MM-DD. Python 3.11 and later also support certain additional ISO forms, covered below.
| Item | Meaning | Example |
|---|---|---|
date_string | ISO-formatted date string | '2024-02-29' |
| Return | datetime.date instance | date(2024, 2, 29) |
| Invalid input | Raises ValueError for an invalid date or unsupported format | '2019-02-30' |
| Introduced | Python 3.7 | Python 3.11 broadened accepted ISO forms |
from datetime import date
parsed = date.fromisoformat('2024-02-29')
print(type(parsed).__name__)
print(parsed.year, parsed.month, parsed.day)
Output:
date
2024 2 29
The original tutorial converts today’s date to a string with strftime(), then parses it with fromisoformat(). That still works, but its output changes with the day and the computer’s local date; a fixed 2019 example output would be misleading.
from datetime import date
dt = date.fromisoformat(date.today().strftime('%Y-%m-%d'))
print(dt)
Output: the current date on the machine running the script, for example 2026-11-13 if executed on that date. If you already have date.today() as a date object, this format-then-parse step is unnecessary.
from datetime import date
now = date.today()
print(now.isoformat())
Output: the current local date in YYYY-MM-DD form. Use date.today() directly for date calculations.
After parsing, access the year, month, and day attributes directly. They are integers, so there is no need to split the original text.
from datetime import date
order_date = date.fromisoformat('2024-12-25')
print('Year:', order_date.year)
print('Month:', order_date.month)
print('Day:', order_date.day)
Output:
Year: 2024
Month: 12
Day: 25
date.fromisoformat() validates calendar dates: February 30 does not exist. Use try/except ValueError when accepting a date string from a form, CSV, or API. This is the error-handling example from the original page.
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
The exact error wording is implementation-dependent; catching ValueError is the reliable part.
Leap-day validity depends on the year. The parser rejects February 29 in a non-leap year.
from datetime import date
for value in ('2024-02-29', '2023-02-29'):
try:
print(value, '=>', date.fromisoformat(value))
except ValueError:
print(value, '=> invalid date')
Output:
2024-02-29 => 2024-02-29
2023-02-29 => invalid date
Use fromisoformat() for supported ISO date strings. Use datetime.strptime(text, format) when the input follows a different, known pattern, such as DD/MM/YYYY. Unlike fromisoformat(), strptime() requires a format pattern.
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-12from datetime import datetime
text = '25/12/2024'
parsed = datetime.strptime(text, '%d/%m/%Y').date()
print(parsed)
Output:
2024-12-25
Do not confuse date.fromisoformat() with datetime.fromisoformat(). Use the latter for ISO date-and-time text such as 2024-06-17T14:30:00+05:30. A numeric timezone offset is retained as timezone information.
from datetime import datetime
stamp = datetime.fromisoformat('2024-06-17T14:30:00+05:30')
print(stamp.date())
print(stamp.time())
print(stamp.utcoffset())
Output:
2024-06-17
14:30:00
5:30:00
This example shows an offset-aware datetime. It does not convert the time to UTC. For date-only values, use date.fromisoformat().
date.isoformat() converts a date object to a standard ISO string; date.fromisoformat() converts that string back to a date object.
from datetime import date
original = date(2024, 3, 15)
text = original.isoformat()
restored = date.fromisoformat(text)
print(text)
print(original == restored)
Output:
2024-03-15
True
From Python 3.11 onward, date.fromisoformat() also accepts compact calendar dates such as 20241225. If your application supports Python 3.7–3.10, prefer the hyphenated YYYY-MM-DD form for compatibility.
from datetime import date
print(date.fromisoformat('20241225'))
Output:
2024-12-25
ISO week notation identifies a date using the week-year, week number and weekday. For example, 2021-W01-1 means Monday of ISO week 1 of 2021. This notation is accepted by date.fromisoformat() in Python 3.11 and later, but not in Python 3.7–3.10.
from datetime import date
print(date.fromisoformat('2021-W01-1'))
Output:
2021-01-04
Not every human-readable date is a supported ISO date. Reduced-precision strings such as 2024-06 and ordinal-date strings such as 2024-169 are not supported by date.fromisoformat(). Reject or normalize incompatible inputs intentionally rather than guessing their meaning.
from datetime import date
for value in ('2024-06', '2024/06/17', '2024-169'):
try:
date.fromisoformat(value)
print(value, ': accepted')
except ValueError:
print(value, ': unsupported')
Output:
2024-06 : unsupported
2024/06/17 : unsupported
2024-169 : unsupported
A web form using an HTML type="date" field commonly sends values like 2024-09-15. Treat the submitted value as untrusted data and validate it on the server; input controls alone are not sufficient validation. This Python example uses a fixed value so you can run it without a web server.
from datetime import date
submitted_value = '2024-09-15'
try:
chosen_date = date.fromisoformat(submitted_value)
print('Accepted date:', chosen_date)
except ValueError:
print('Please enter a valid date in YYYY-MM-DD format.')
Output:
Accepted date: 2024-09-15
For supported dates, convert the strings into date objects before sorting. This avoids relying on string layout and works with downstream date arithmetic.
from datetime import date
values = ['2024-12-31', '2024-01-03', '2024-06-15']
ordered = sorted(date.fromisoformat(x) for x in values)
for value in ordered:
print(value)
Output:
2024-01-03
2024-06-15
2024-12-31
Once the input is a date object, compare it with other dates using <, <=, > or >=.
from datetime import date
cutoff = date.fromisoformat('2024-06-01')
events = ['2024-05-20', '2024-06-15', '2024-07-01']
for value in events:
when = date.fromisoformat(value)
if when >= cutoff:
print(value)
Output:
2024-06-15
2024-07-01
Subtracting two date objects produces a timedelta. This is more dependable than manually subtracting day numbers.
from datetime import date
start = date.fromisoformat('2024-01-01')
finish = date.fromisoformat('2024-01-10')
print((finish - start).days, 'days')
Output:
9 days
When reading CSV records, parse each field explicitly and report invalid values without stopping the entire import. This simplified example uses an in-memory list; no files or external packages are required.
from datetime import date
rows = [('A101', '2024-02-29'), ('A102', '2024-02-30')]
for reference, text in rows:
try:
parsed = date.fromisoformat(text)
print(reference, parsed)
except ValueError:
print(reference, 'invalid date:', text)
Output:
A101 2024-02-29
A102 invalid date: 2024-02-30
| Problem | Fix |
|---|---|
ValueError: Invalid isoformat string | Check separators, unsupported precision, extra whitespace, and actual calendar validity. Use strip() only if trimming surrounding whitespace is acceptable. |
TypeError when passing a date object | fromisoformat() accepts a string. If you already have a date object, keep using it directly. |
| Today’s example does not show the tutorial’s date | date.today() changes and uses the local system date; it cannot have a permanent output. |
| Compact/ISO-week input fails in older Python | The extended formats shown above require Python 3.11 or later. Use YYYY-MM-DD for Python 3.7–3.10. |
| Input contains a time or UTC offset | Use datetime.fromisoformat() for a full ISO timestamp, then call .date() if you only need its calendar date. |
from datetime import date
raw = ' 2024-06-17 '
print(date.fromisoformat(raw.strip()))
Output:
2024-06-17
Try these before checking your answers in the Colab notebook: parse your birthday from an ISO string; reject an impossible day; convert a DD/MM/YYYY date with strptime(); compare two holiday dates; and make an event list sorted chronologically. The notebook provides starter code and self-checking assertions.
date.fromisoformat() return?It returns a datetime.date object, not a string and not a datetime.datetime timestamp.
DD/MM/YYYY?No. Parse that format using datetime.strptime(value, '%d/%m/%Y').date().
ValueError is raised. Use try/except for inputs you cannot trust.
date.fromisoformat() and datetime.fromisoformat()?The first creates a date-only object. The second creates a date-and-time object and can parse supported timestamp and timezone-offset strings.
Python 3.11 broadened support beyond YYYY-MM-DD. For older versions use the hyphenated representation.
fromisoformat() the same as isoformat()?No. isoformat() generates ISO text from an object, while fromisoformat() parses text into an object.
Continue learning with these Plus2Net Python lessons:
Reference: Python official date.fromisoformat() documentation.
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.