Function Name
fromordinal
Function Signature
@classmethod fromordinal(ordinal)
Return Value
Returns the Gregorian date corresponding to a given Gregorian ordinal.
Parameter
ordinal – The Gregorian ordinal for which the date needs to be found.
Function Overview
- The method fromordinal() of the Python date class computes the date for a given Gregorian ordinal and returns the value.
- The opposite is performed by the toordinal() method, which converts a Gregorian date to a Gregorian ordinal.
Note
When a negative value or an ordinal beyond the value returned by the date.max.toordinal() is passed to the parameter ordinal, toordinal() method raises a ValueError.
Exceptions raised
ValueError
Example 1
# ----- Example Python program to get Gregorian date from Ordinal -----
import datetime
# Gregorian ordinal
ordinal = 737425
date = datetime.date.fromordinal(ordinal)
print("New year 2020 from ordinal %d:%s"%(ordinal, date))
# Day 1 of Gregorian calendar
date = datetime.date.fromordinal(1)
print("Date for the first day of Gregorian calendar:%s"%date)
# Maximum date
print("Maximum ordinal supported in Python Standard Library is %s"%date.max.toordinal())Output
New year 2020 from ordinal 737425:2020-01-01
Date for the first day of Gregorian calendar:0001-01-01
Maximum ordinal supported in Python Standard Library is 3652059Example 2
import datetime
# Negative value given for ordinal
negativeOrdinal = -52;
beyondMax = datetime.date.max.toordinal()
try:
beforeGregorian1 = datetime.date.fromordinal(negativeOrdinal)
print("Some date before 1st date in Gregorian calendar:%s"%beforeGregorian1)
except ValueError as Ex:
print(Ex)
try:
afterMax = datetime.date.fromordinal(beyondMax + 1)
print("Date for Gregorian ordinal beyond %d:%s"%(beyondMax, afterMax))
except ValueError as Ex:
print(Ex)Output
ordinal must be >= 1
year 10000 is out of range