What is date.fromisoformat() in Python?

The fromisoformat() method from the date class is used to generate a date object to convert the argument string (ISO format). It takes a string argument and converts it into an ISO calendar date instance. The standard ISOInternational Organization for Standardization date format is “yyyy-mm-dd.” (Year-Month-Day).

Note: The date class is obtained from datetime module.

Syntax


fromisoformat(date_string)

Parameters

This method takes a single argument value:

  • date_string: It shows the defined ISOInternational Organization for Standardization format string whose date type object will be created.

Return value

date-type-object: It will transform a string argument value (ISOInternational Organization for Standardization format) into a date object in Gregorian calendar format.

Example

The codes below show how fromisformat() behaves.

# Import the datetime module
import datetime
# intialize the date
ISO_date = "2021-12-18";
# Call the fromisoformat() method to create the datetime.date object
gregorian_date = datetime.date.fromisoformat(ISO_date);
# Print the newly created date object
print("String as Date object: %s" %gregorian_date);

Explanation

  • Line 4: We have an ISO_date string type variable that contains 2021-12-18 in ISO format.
  • Line 6: This method takes a string as an argument and returns a date type object in gregorian_date variable.

Example

# Import date class from datetime module
from datetime import date
# converting string argument in date format
# to date type object
date_object = date.fromisoformat('2021-12-25')
# Print the newly created date object
print("The newly created date object is : %s" %date_object);

Explanation

  • Line 5: Covering date in string format '2021-12-25' to date_object.
  • Line 7: Printing date_object on console.

Example

# Import date class from datetime module
from datetime import date
# intialize today variable with today's date
# converting date to a String object
today= str(date.today());
# printing date as string
print("Date as string: %s" %today)
# invoking fromisoformat() method
# to create the datetime.date type object
mydate = date.fromisoformat(today);
# Print the newly created date object
print("The newly created date object is : %s" %mydate);

Explanation

  • Line 5: In this line, date.today() method is extracting today’s date and returning a date object. Then, str() is converting date object to a string object today.
  • Line 7: Printing today on the console.
  • Line 10: Calling fromisoformat() method from date class and converting today (from ISO formatted date) to mydate as a date object.
  • Line 12: Printing mydate on the console.

Free Resources