Python date toordinal() Method with Example

Python date.toordinal() Method: In this tutorial, we will learn about the toordinal() method of date class in Python with its usage, syntax, and examples. By Hritika Rajput Last updated : April 22, 2023

Python date.toordinal() Method

The date.toordinal() method returns the proleptic Gregorian ordinal of the date, where January 1 of year 1 has ordinal 1. If January 1 of year 1 has ordinal number 1 then January 2 year 1 will have ordinal number 2 and so on. It is an instance method which means that it works on an instance of the class.

Module

The following module is required to use toordinal() method:

import datetime

Class

The following class is required to use toordinal() method:

from datetime import date

Syntax

The following is the syntax of toordinal() method:

toordinal()

Parameter(s)

The following are the parameter(s):

  • None

Return Value

The return type of this method is a number which is the ordinal number of that date in Gregorian calendar.

Example of date toordinal() Method in Python

## importing date class

from datetime import date

## Creating an instance
x = date(2020,10,27)
d = x.toordinal()
print("Ordinal number of date ",x," is:", d)
print()

## Using today' date
x = date.today()
d = x.toordinal()
print("Ordinal number of date ",x," is:", d)
print()

x = date(1, 1, 1)
d = x.toordinal()
print("Ordinal number of the earliest possible date allowed",x," is:", d)
print()

x = date(9999, 12, 31)
d = x.toordinal()
print("Ordinal number of the largest maximum date allowed",x," is:", d)
print()

Output

Ordinal number of date  2020-10-27  is: 737725

Ordinal number of date  2020-04-29  is: 737544

Ordinal number of the earliest possible date allowed 0001-01-01  is: 1

Ordinal number of the largest maximum date allowed 9999-12-31  is: 3652059

Note: Date should be in the given range otherwise it will show a ValueError.

Example 2

## importing date class

from datetime import date

## Creating an instance
x = date(99999, 12, 31)
d = x.toordinal()
print("Ordinal number of the date",x," is:", d)
print()

Output

Traceback (most recent call last):
  File "main.py", line 6, in <module>
    x = date(99999, 12, 31)
ValueError: year 99999 is out of range



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.