Python – datetime.toordinal() Method with Example
Last Updated :
06 Sep, 2021
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
import datetime
dateToday = datetime.date.today()
toOrdinal = dateToday.toordinal()
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
from datetime import datetime
dateIs = datetime( 189 , 0 , 0 )
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
from datetime import datetime
dateIs = datetime( 1 , 1 , 1 , 0 , 0 , 0 , 0 )
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
Share your thoughts in the comments
Please Login to comment...