The Wayback Machine - https://web.archive.org/web/20240829152433/https://www.geeksforgeeks.org/python-datetime-toordinal-method-with-example/
Open In App

Python – datetime.toordinal() Method with Example

Last Updated : 06 Sep, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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



Previous Article
Next Article

Similar Reads

toordinal() Function Of Datetime.date Class In Python
The toordinal() function is used to return the proleptic Gregorian ordinal of a specified datetime instance. Note: The Proleptic Gregorian ordinal gives the number of days elapsed from the date 01/Jan/0001. And here ordinal is called Proleptic since the Gregorian calendar itself is followed from October 1582. Syntax: toordinal() Parameters: This fu
2 min read
Python | Pandas Timestamp.toordinal
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Timestamp.toordinal() function return proleptic Gregorian ordinal. January 1 of year 1 is day 1. Function return the ordinal valu
2 min read
Python DateTime - DateTime Class
DateTime class of the DateTime module as the name suggests contains information on both dates as well as time. Like a date object, DateTime assumes the current Gregorian calendar extended in both directions; like a time object, DateTime assumes there are exactly 3600*24 seconds in every day. But unlike the date class, the objects of the DateTime cl
5 min read
How to convert a Python datetime.datetime to excel serial date number
This article will discuss the conversion of a python datetime.datetime to an excel serial date number. The Excel "serial date" format is actually the number of days since 1900-01-00. The strftime() function is used to convert date and time objects to their string representation. It takes one or more inputs of formatted code and returns the string r
3 min read
How to Fix - "datetime.datetime not JSON serializable" in Python?
In this article, we are going to learn how to fix the error "datetime.datetime not JSON serializable" in Python. datetime.datetime is a class in the Python datetime module that represents a single point in time. This class is not natively supported by the JSON (JavaScript Object Notation) format, which means that we cannot serialize a datetime.date
4 min read
Python datetime.tzname() Method with Example
tzname() method is used in the DateTime class of module DateTime. This method is used to return the time zone name of the DateTime object passed, as a string. Syntax: tzname() Return type: It will return the time zone name of the DateTime object passed, as a string. So first we need to import the module DateTime, and to get the timezone of the exac
2 min read
Python datetime.timetz() Method with Example
The timetz() function manipulates the objects of the DateTime class of the DateTime module. This function uses an instance method given to it via reference, and converts them, and returns a time object with the same hour, minute, second, microsecond, and fold and tzinfo attributes. Syntax: timetz() Parameters: This function does not accept any para
3 min read
Python DateTime - time.replace() Method with Example
In this article, we will discuss the time.replace() method in Python. This method is used to manipulate objects of time class of module datetime. It is used to replace the time with the same value, except for those parameters given new values by whichever keyword arguments. Syntax: replace(year=self.year, month=self.month, day=self.day) Parameters:
2 min read
Python DateTime weekday() Method with Example
In this article, we will discuss the weekday() function in the DateTime module. weekday() function is used to get the week number based on given DateTime. It will return the number in the range of 0-6 RepresentationMeaning0Monday1Tuesday2Wednesday3Thursday4Friday5Saturday6Sunday It will take input as DateTime in the format of "(YYYY, MM, DD, HH, MM
3 min read
Python datetime.utcoffset() Method with Example
The utcoffset() function is used to return a timedelta object that represents the difference between the local time and UTC time. This function is used in used in the datetime class of module datetime.Here range of the utcoffset is "-timedelta(hours=24) &lt;= offset &lt;= timedelta(hours=24)".If the offset is east of UTC, then it is considered posi
2 min read
Python DateTime astimezone() Method
The astimezone() function is used to return a DateTime instance according to the specified time zone parameter tz. Note: The returned DateTime instance is having the new UTC offset value as per the tz parameter. And If this function does not take parameter tz, then the returned DateTime object will have the local date, time, and time zone. Syntax:
2 min read
Isoweekday() Method Of Datetime Class In Python
Isoweekday() is a method of the DateTime class that tells the day of the given date. It returns an integer that corresponds to a particular day. Syntax: datetime.isoweekday() Parameters: None Return Value: It returns an integer which corresponds to a day as per the table Integer ReturnedDay of the week1Monday2Tuesday3Wednesday4Thursday5Friday6Satur
3 min read
Isocalendar() Method Of Datetime Class In Python
The isocalendar() function is used to return a tuple of ISO Year, ISO Week Number, and ISO Weekday. Note: According to ISO standard 8601 and ISO standard 2015, Thursday is the middle day of a week.Therefore, ISO years always start with Monday.ISO year can start as yearly as 29th January or as late as 4th January of a Gregorian calendar.ISO years ca
2 min read
Isoformat() Method Of Datetime Class In Python
In this example, we will learn How to get date values in ISO 8601 format using Python. The Isoformat() function is used to return a string of date, time, and UTC offset to the corresponding time zone in ISO 8601 format. The standard ISO 8601 format is all about date formats for the Gregorian calendar. This format prescribes that a calendar date nee
4 min read
Pandas Series dt.to_period() Method | Convert DateTime to Period Format
The Pandas dt.to_period() method converts the underlying data of the given Series object to PeriodArray/Index at a particular frequency. It is used to convert a DateTime series to a period series with a specific frequency, such as daily, monthly, quarterly, or yearly periods. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-12-31', '201
2 min read
fromisoformat() Function Of Datetime.date Class In Python
The fromisoformat() function is used to constructs a date object from a specified string that contains a date in ISO format. i.e., yyyy-mm-dd. Syntax: @classmethod fromisoformat(date_string) Parameters: This function accepts a parameter which is illustrated below: date_string: This is the specified ISO format i.e., yyyy-mm-dd date string whose date
2 min read
Working with Datetime Objects and Timezones in Python
In this article, we are going to work with Datetime objects and learn about their behavior when Time zones are introduced. We are going to be working with the Python datetime module. Getting a Datetime objectMethod 1: Using now() method A very easy way to get a Datetime object is to use the datetime.now() method. A DateTime object is an instance/ob
5 min read
Create Python Datetime from string
In this article, we are going to see how to create a python DateTime object from a given string. For this, we will use the datetime.strptime() method. The strptime() method returns a DateTime object corresponding to date_string, parsed according to the format string given by the user. Syntax: datetime.strptime(date_string, format)Converting string
4 min read
Python - datetime.tzinfo()
The DateTime class provides various functions to manipulate the date and time intervals. The DateTime object which you use in datetime.now() is actually the object of the DateTime class. These objects help us use the functions on dates and times. Note: For more information, refer to Python datetime module with examples DateTime.tzinfo() The datetim
4 min read
Manipulate Date and Time with the Datetime Module in Python
Have you ever wondered about working with Date and Time with Python? If you have then you must have noticed that Python does not provide any built-in method to work with either Date or Time. But thanks to the DateTime module that comes pre-loaded with Python's standard utility modules we can easily manipulate date and time according to our own need
9 min read
How to convert timestamp string to datetime object in Python?
Python has a module named Datetime to work with dates and times. We did not need to install it separately. It is pre-installed with the Python package itself. A UNIX timestamp is several seconds between a particular date and January 1, 1970, at UTC. Input: "2023-07-21 10:30:45"Output: 2023-07-21 10:30:45Explanation: In This, We are converting a tim
2 min read
How to change the Pandas datetime format in Python?
Prerequisites: Pandas The date-time default format is "YYYY-MM-DD". Hence, December 8, 2020, in the date format will be presented as "2020-12-08". The datetime format can be changed and by changing we mean changing the sequence and style of the format. Function used strftime() can change the date format in python. Syntax: strftime(format) Where, fo
1 min read
How to add and subtract days using DateTime in Python?
As we know date and time are used in programs where we have to keep track of date and time, so it is necessary to have a module to manipulate date and time. In Python, a DateTime module deals with dates and times. Datetime module is built into Python standard library. Datetime module consists of the following classes: Name Description 1.dateIt show
3 min read
Basic DateTime Operations in Python
Python has an in-built module named DateTime to deal with dates and times in numerous ways. In this article, we are going to see basic DateTime operations in Python. There are six main object classes with their respective components in the datetime module mentioned below: datetime.datedatetime.timedatetime.datetimedatetime.tzinfodatetime.timedeltad
12 min read
How to convert DateTime to integer in Python
Python provides a module called DateTime to perform all the operations related to date and time. It has a rich set of functions used to perform almost all the operations that deal with time. It needs to be imported first to use the functions and it comes along with python, so no need to install it separately. Here, we deal with a special date objec
2 min read
Python SQLite - Working with Date and DateTime
SQLite does not support built-in DateTime storage a class, but SQLite allows us to work with timestamp types. We can store and retrieve Python date and datetime information stored in the SQLite database tables by converting them to Python date and datetime types and vice-versa. While inserting the datetime value, the python sqlite3 module converts
4 min read
How to convert Python's .isoformat() string back into datetime object
In this article, we will learn how to convert Pythons .isoFormat() string back into a datetime object. Here we are using the current time and for that, we will store the current time in the current_time variable. The function now() of this module, does the job perfectly. Example: Getting current time C/C++ Code from datetime import datetime current
1 min read
isocalendar() Function Of Datetime.date Class In Python
The isocalendar() function is used to return a tuple containing ISO Year, ISO Week Number, and ISO Weekday. Note: According to ISO standard 8601 and ISO standard 2015, Thursday is the middle day of a week.Therefore, ISO years always start with Monday.ISO years can have either 52 full weeks or 53 full weeks.ISO years do not have any fractional weeks
2 min read
fromtimestamp() Function Of Datetime.date Class In Python
The fromtimestamp() function is used to return the date corresponding to a specified timestamp. Note: Here the timestamp is ranging from the year 1970 to the year 2038, and this function does not consider leap seconds if any present in the timestamp. This function is a class method. Syntax: @classmethod fromtimestamp(timestamp) Parameters: This fun
2 min read
ctime() Function Of Datetime.date Class In Python
The ctime() function is used to return a string containing the date and time. Syntax: ctime() Parameters: This function does not accept any parameter. Return values: This function returns a string containing the date and time. The format of the string representation: The string is of 24-character length.Week is printed as a three-letter word.Sun, M
2 min read
Article Tags :
Practice Tags :