The fromisoformat
method is used to convert a string representing a date and time in ISO 8601 format into a datetime.datetime
object in Python.
The argument passed to the fromisoformat
method must be a string. If a different data type is passed, such as an integer or a float, a TypeError
will be raised with the message “argument must be str”. This is because the fromisoformat
method expects the argument to be a string representing a date and time in a specific format.
Here’s an example to demonstrate the usage of the fromisoformat
method:
import datetime
# Correct usage
date_string = "2022-12-31T23:59:59"
datetime_obj = datetime.datetime.fromisoformat(date_string)
print(datetime_obj) # Output: 2022-12-31 23:59:59
# Incorrect usage
incorrect_date = 20221231235959
incorrect_datetime_obj = datetime.datetime.fromisoformat(incorrect_date)
# Raises TypeError: argument must be str
In the example above, we first pass a correct ISO 8601 formatted date string to the fromisoformat
method, and it successfully converts it into a datetime.datetime
object. However, in the incorrect usage, we pass an integer instead of a string, which raises a TypeError
with the specified error message.