Open In App

fromisoformat() method

Last Updated : 22 Aug, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

datetime.fromisoformat() is a built-in method in Python’s datetime module that converts a string formatted in ISO 8601 format (e.g., YYYY-MM-DD or YYYY-MM-DD HH:MM:SS) into a datetime.datetime object.

Example:

Python
from datetime import datetime
s = "2025-07-21 10:30:45"
dt = datetime.fromisoformat(s)
print(dt)

Output
2025-07-21 10:30:45

Explanation: The string is in a valid ISO format. fromisoformat() parses it directly into a datetime.datetime object.

Syntax

datetime.fromisoformat(date_string)

Parameter: date_string is a string in ISO 8601 format (e.g., '2025-07-14' or '2025-07-14 12:30:00').

Returns: A datetime.datetime object representing the given ISO-format string.

Examples

Example 1: Basic ISO date string

Python
from datetime import datetime
s = "2025-07-14"
dt = datetime.fromisoformat(s)
print(dt)

Output
2025-07-14 00:00:00

Explanation: Since no time is specified, it defaults to midnight (00:00:00).

Example 2: ISO date and time string

Python
from datetime import datetime
s = "2025-07-14 15:45:30"
dt = datetime.fromisoformat(s)
print(dt)

Output
2025-07-14 15:45:30

Explanation: The date and time are parsed accurately from the ISO string.

Example 3: ISO string with microseconds

Python
from datetime import datetime
s = "2025-07-14 15:45:30.123456"
dt = datetime.fromisoformat(s)
print(dt)

Output
2025-07-14 15:45:30.123456

Explanation: The microseconds part is also preserved while converting the string into a datetime object.

Example 4: ISO string with timezone offset

Python
from datetime import datetime
s = "2025-07-14T10:30:00+05:30"
dt = datetime.fromisoformat(s)
print(dt)

Output
2025-07-14 10:30:00+05:30

Explanation: The function parses ISO strings with timezone offsets correctly, returning an aware datetime object.

Example 5: Invalid Format Raises Error

Python
from datetime import datetime
s = "14-07-2025"
dt = datetime.fromisoformat(s) 

Output

Hangup (SIGHUP)
Traceback (most recent call last):
File "/home/guest/sandbox/Solution.py", line 3, in <module>
dt = datetime.fromisoformat(s)
ValueError: Invalid isoformat string: '14-07-2025'

Explanation: fromisoformat() only accepts ISO 8601-compliant strings. Formats like DD-MM-YYYY are not supported and will raise an error.


Article Tags :
Practice Tags :

Similar Reads