Monday, June 15, 2026
HomeLanguagesPython – datetime.toordinal() Method with Example

Python – datetime.toordinal() Method with Example

datetime.toordinal() is a simple method used to manipulate the objects of DateTime class. It returns proleptic Gregorian ordinal of the date, where January 1 of year 1 has ordinal 1. The function returns the ordinal value for the given DateTime object.

If January 1 of year 1 has ordinal number 1 then, January 2 year 1 will have ordinal number 2, and so on.

Syntax: 

datetimeObj.toordinal()

Parameters: None

Returns: Ordinal Value

Given below are some implementations for the same.

Example 1: Use datetime.toordinal() function to return the Gregorian ordinal for the given datetime object using date.today() class of datetime module.

Python3




# Python3 code to demonstrate
# Getting Ordinal value using
# toordinal().
 
# importing datetime module for today()
import datetime
 
# using date.today() to get todays date
dateToday = datetime.date.today()
 
# Using toordinal() to generate ordinal value.
toOrdinal = dateToday.toordinal()
 
# Prints Ordinal Value of Todays Date.
print(f"Ordinal of date {dateToday} is {toOrdinal}")


Output

Ordinal of date 2021-08-03 is 738005

Note: Attributes of DateTime class should be in given range otherwise it will show a ValueError

Example 2: Example to show the parameters needs to be in the range

Python3




# importing datetime class
from datetime import datetime
 
# Creating an instance of datetime.
dateIs = datetime(189, 0, 0)
 
# Using toordinal() method
toOrdinal = dateIs.toordinal()
print(f"Ordinal value of Earliest Datetime {dateIs} is {toOrdinal}")


Output:

Traceback (most recent call last):

  File “/home/2ecd5f27fbc894dc8eeab3aa6559c7ab.py”, line 5, in <module>

    dateIs = datetime(189,0,0)

ValueError: month must be in 1..12

Example 3: Use datetime.toordinal() function to return the Gregorian ordinal for the given DateTime object.

Python3




# importing datetime class
from datetime import datetime
 
# Creating an instance of datetime.
dateIs = datetime(1, 1, 1, 0, 0, 0, 0)
 
# Using toordinal() method
toOrdinal = dateIs.toordinal()
print(f"Ordinal value of Earliest Datetime {dateIs} is {toOrdinal}")
 
print()
 
dateIs = datetime(9999, 12, 31, 23, 59, 59)
toOrdinal = dateIs.toordinal()
print(f"Ordinal value of Latemost Datetime {dateIs} is {toOrdinal}")


Output:

Ordinal value of Earliest Datetime 0001-01-01 00:00:00 is 1

Ordinal value of Latemost Datetime 9999-12-31 23:59:59 is 3652059

RELATED ARTICLES

2 COMMENTS

Most Popular

Dominic
32515 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6897 POSTS0 COMMENTS
Nicole Veronica
12013 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12109 POSTS0 COMMENTS
Shaida Kate Naidoo
7019 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6976 POSTS0 COMMENTS
Umr Jansen
6964 POSTS0 COMMENTS