Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Pandas - Return proleptic Gregorian ordinal
To return proleptic Gregorian ordinal, use the timestamp.toordinal() method. The proleptic Gregorian ordinal is the number of days since January 1 of year 1, where January 1 of year 1 is day 1.
Understanding Proleptic Gregorian Ordinal
The proleptic Gregorian calendar extends the Gregorian calendar backward to dates before its introduction in 1582. The ordinal represents the total number of days elapsed since the theoretical date January 1, 1 AD.
Basic Usage
First, import the required library and create a timestamp object ?
import pandas as pd
# Create the timestamp object
timestamp = pd.Timestamp(2021, 9, 18, 11, 50, 20, 33)
print("Timestamp:", timestamp)
# Return proleptic Gregorian ordinal
ordinal = timestamp.toordinal()
print("Gregorian ordinal:", ordinal)
Timestamp: 2021-09-18 11:50:20.000033 Gregorian ordinal: 738051
Multiple Date Examples
Let's see the ordinal values for different dates to understand the pattern ?
import pandas as pd
dates = [
pd.Timestamp(1, 1, 1), # January 1, year 1
pd.Timestamp(2000, 1, 1), # Y2K
pd.Timestamp(2021, 9, 18), # Random date
pd.Timestamp(2023, 12, 31) # End of 2023
]
for date in dates:
print(f"{date.strftime('%Y-%m-%d')}: {date.toordinal()}")
0001-01-01: 1 2000-01-01: 730120 2021-09-18: 738051 2023-12-31: 738886
Converting Back from Ordinal
You can also convert an ordinal back to a date using pd.Timestamp.fromordinal() ?
import pandas as pd
# Convert ordinal back to timestamp
ordinal = 738051
timestamp = pd.Timestamp.fromordinal(ordinal)
print(f"Ordinal {ordinal} corresponds to: {timestamp}")
# Verify it matches our original date
original = pd.Timestamp(2021, 9, 18)
print(f"Original date: {original}")
print(f"Match: {timestamp.date() == original.date()}")
Ordinal 738051 corresponds to: 2021-09-18 00:00:00 Original date: 2021-09-18 00:00:00 Match: True
Practical Use Cases
The ordinal representation is useful for date calculations and storing dates efficiently ?
import pandas as pd
start_date = pd.Timestamp(2021, 1, 1)
end_date = pd.Timestamp(2021, 12, 31)
# Calculate days between dates using ordinals
days_difference = end_date.toordinal() - start_date.toordinal()
print(f"Days in 2021: {days_difference + 1}")
# Check if 2021 is a leap year
print(f"Is 2021 a leap year: {days_difference == 364}")
Days in 2021: 365 Is 2021 a leap year: False
Conclusion
The toordinal() method converts Pandas timestamps to proleptic Gregorian ordinals, representing days since January 1, year 1. This is useful for date arithmetic, storage efficiency, and calendar calculations.
