Python datetime.date.date.toordinal() Method

Vaibhav Vaibhav Jan 30, 2023
  1. Syntax
  2. Example 1: Use datetime.date.date.toordinal to Get Gregorian Ordinal for a Date
  3. Example 2: Use datetime.date.date.toordinal to Get Date From an Ordinal Date
Python datetime.date.date.toordinal() Method

The datetime module is a built-in module in the Python programming language. This module offers a class date that helps represent dates.

This class is concrete and comprehensive. It provides various member functions and attributes to perform numerous operations and calculations.

The date class’ objects have a method, toordinal(), that returns the proleptic Gregorian ordinal of a date, where January 1 of year 1 has ordinal 1.

Syntax

<date-object > .toordinal()

It is a method available on date instances.

Parameters

The toordinal() method doesn’t accept any parameters.

Returns

The toordinal() method returns the proleptic Gregorian ordinal of a date, where January 1 of year 1 has ordinal 1.

Example 1: Use datetime.date.date.toordinal to Get Gregorian Ordinal for a Date

import datetime

d = datetime.date.today()
print("Date:", d)
print("Ordinal Date:", d.toordinal())
print("Ordinal Date Type:", type(d.toordinal()))

Output:

Date: 2022-08-30
Ordinal Date: 738397
Ordinal Date Type: <class 'int'>

The Python code above first gets a date object for the current date using the today() method. Next, it receives an ordinal value for the date.

Note that the ordinal date is of type integer.

Example 2: Use datetime.date.date.toordinal to Get Date From an Ordinal Date

import datetime

d = datetime.date.today()
od = d.toordinal()
print("Date:", d)
print("Ordinal Date:", od)
print("Original Date:", datetime.date.fromordinal(od))

Output:

Date: 2022-08-31
Ordinal Date: 738398
Original Date: 2022-08-31

The Python code above creates a date instance for the current date and gets its ordinal form. Next, using the ordinal form and the fromordinal() method, it extracts the original date from it.

The fromordinal() method is a part of the datetime.date module, which accepts an ordinal integer date.

Vaibhav Vaibhav avatar Vaibhav Vaibhav avatar

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.

Related Article - Python Datetime