What is the datetime.toordinal() method in Python?
Overview
The datetime.toordinal() method is used to manipulate the DateTime class object to get their ordinal value. It returns a proleptic Gregorian ordinal of the date.
For example, the ordinal value for January 1 of year 1 is 1. Similarly, the ordinal value for January 5 of year 1 is 5, and so on.
Syntax
date.toordinal()
Parameters
This method does not take any argument value(s).
Return value
This method returns an integer type ordinal value.
Code examples
Let’s look at different examples of the date.toordinal() method in use:
# Coding example # 1# importing date class from datetime modulefrom datetime import date# Getting today's datetodayDate = date.today()# using toordinal() to produce ordinal valueordinalValue = todayDate.toordinal()# Prints ordinal value of todayDateprint("Ordinal of date ",todayDate, " is ", ordinalValue)
Code explanation
- Line 3: We import the
dateclass from thedatetimemodule. - Line 5: We extract today’s date from the
todayDatevariable. - Line 7: We call the
toordinal()method to extract the ordinal value. - Line 9: We print the ordinal value of the
todayDatevariable.
Here is another example, comparing two different DateTime objects and their ordinal values:
# Coding example # 2# importing datetime class# from datetime modulefrom datetime import datetime# Creating an instance of datetime.mydate = datetime(1, 2, 1, 0, 0, 1)# Calling toordinal() methodordinalValue = mydate.toordinal()print(f"Frist DateTime instance {mydate} is {ordinalValue}")# Creating another instance of datetime.mydate = datetime(2000, 1, 1, 20, 10, 59)# Calling toordinal() methodordinalValue = mydate.toordinal()print(f"Second DateTime instance {mydate} is {ordinalValue}")
Code explanation
- Line 6: We have a
DateTimeinstance with0001-02-01 00:00:01values. It contains both the date and time. - Line 8: We call the
toordinal()method to extract the ordinal value. - Line 11: We have a DateTime instance with
2000-01-01 20:10:59values. It contains both the date and time. - Line 13: We call the
toordinal()method to extract the ordinal value.