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 module
from datetime import date
# Getting today's date
todayDate = date.today()
# using toordinal() to produce ordinal value
ordinalValue = todayDate.toordinal()
# Prints ordinal value of todayDate
print("Ordinal of date ",todayDate, " is ", ordinalValue)

Code explanation

  • Line 3: We import the date class from the datetime module.
  • Line 5: We extract today’s date from the todayDate variable.
  • Line 7: We call the toordinal() method to extract the ordinal value.
  • Line 9: We print the ordinal value of the todayDate variable.

Here is another example, comparing two different DateTime objects and their ordinal values:

# Coding example # 2
# importing datetime class
# from datetime module
from datetime import datetime
# Creating an instance of datetime.
mydate = datetime(1, 2, 1, 0, 0, 1)
# Calling toordinal() method
ordinalValue = 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() method
ordinalValue = mydate.toordinal()
print(f"Second DateTime instance {mydate} is {ordinalValue}")

Code explanation

  • Line 6: We have a DateTime instance with 0001-02-01 00:00:01 values. 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:59 values. It contains both the date and time.
  • Line 13: We call the toordinal() method to extract the ordinal value.

Free Resources