from datetime import date
my_ordinal=date.today().toordinal()
print("Today toordinal value : ", my_ordinal)
Output
Today toordinal value : 737319
Getting todays and tomorrows toordinal. We used timedelta here to get tomorrow's date object.
from datetime import date, datetime, timedelta
print("Today toordinal : ", date.today().toordinal())
tomorrow=date.today() + timedelta(days=1)
print("Tomorrow toordinal : ", tomorrow.toordinal())
Output is here
Today toordinal : 737319
Tomorrow toordinal : 737320
We can create a date object and then get the value
import datetime
dt=datetime.datetime(2019,5,24) # Year, Month, date as input
print(dt.toordinal())
Output
737203
We can check the above data ( todays date )
dt=datetime.datetime(2019,9,16) # Year, Month, date as input
print(dt.toordinal())
Output
737318
We can use toordinal() to calculate the number of days between two dates.
from datetime import date
start_date = date(2024, 1, 1)
end_date = date(2024, 12, 31)
days_difference = end_date.toordinal() - start_date.toordinal()
print("Days between start and end date:", days_difference)
We can use fromordinal() to convert an ordinal number back to a date.
from datetime import date
ordinal_value = 738000
dt = date.fromordinal(ordinal_value)
print("Date from ordinal:", dt)
Leap years add complexity when calculating day differences. Let's check the effect of a leap year.
from datetime import date
date1 = date(2020, 2, 28)
date2 = date(2020, 3, 1)
print("Days between Feb 28 and Mar 1 in 2020:", date2.toordinal() - date1.toordinal())
We can find the ordinal value of the first day of any year.
from datetime import date
for year in range(2020, 2025):
print(f"First day of {year}:", date(year, 1, 1).toordinal())
We can generate a sequence of dates by iterating over a range of ordinal values.
from datetime import date
start_date = date(2025, 2, 8)
end_date = date(2025, 2, 12)
for ordinal in range(start_date.toordinal(), end_date.toordinal() + 1):
current_date = date.fromordinal(ordinal)
print(current_date)
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.