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
Note: The
dateclass is obtained fromdatetimemodule.
Syntax
fromisoformat(date_string)
Parameters
This method takes a single argument value:
date_string: It shows the defined format string whoseISO International Organization for Standardization datetype object will be created.
Return value
date-type-object: It will transform a string argument value (
Example
The codes below show how fromisformat() behaves.
# Import the datetime moduleimport datetime# intialize the dateISO_date = "2021-12-18";# Call the fromisoformat() method to create the datetime.date objectgregorian_date = datetime.date.fromisoformat(ISO_date);# Print the newly created date objectprint("String as Date object: %s" %gregorian_date);
Explanation
- Line 4: We have an
ISO_datestring type variable that contains2021-12-18in ISO format. - Line 6: This method takes a string as an argument and returns a
datetype object ingregorian_datevariable.
Example
# Import date class from datetime modulefrom datetime import date# converting string argument in date format# to date type objectdate_object = date.fromisoformat('2021-12-25')# Print the newly created date objectprint("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_objecton console.
Example
# Import date class from datetime modulefrom datetime import date# intialize today variable with today's date# converting date to a String objecttoday= str(date.today());# printing date as stringprint("Date as string: %s" %today)# invoking fromisoformat() method# to create the datetime.date type objectmydate = date.fromisoformat(today);# Print the newly created date objectprint("The newly created date object is : %s" %mydate);
Explanation
- Line 5: In this line,
date.today()method is extracting today’s date and returning adate object. Then,str()is convertingdate objectto a string objecttoday. - Line 7: Printing
todayon the console. - Line 10: Calling
fromisoformat()method from date class and convertingtoday(from ISO formatted date) tomydateas a date object. - Line 12: Printing
mydateon the console.