Converting A Date To Day of the Year In Python
Table of Contents
This is a quick note on how to take a date and convert it to the day of the year (and back again) using python.
Date To Day of Year
We're going to use python's built-in datetime object to create the date then convert it to a timetuple using its timetuple method. The timetuple has an attribute tm_yday
which is the number of days in the year that the date represents.
from datetime import datetime
YEAR, MONTH, DAY = 2023, 2, 7
DAY_OF_YEAR = datetime(YEAR, MONTH, DAY).timetuple().tm_yday
print(DAY_OF_YEAR)
38
So, February 7, 2023 is the 38th day of the year.
Day Of Year To Date
Now to go in the other direction we start with the first day of the year (represented as a datetime object) and add the number of days into the year we want. You can't create a datetime object with day zero so we need to start it on day one and then subtract one day from the number of days that we want.
from datetime import timedelta
JANUARY = 1
date = datetime(YEAR, JANUARY, 1) + timedelta(DAY_OF_YEAR - 1)
print(date.strftime("%Y-%m-%d"))
2023-02-07
Easy-peasey.
Source
- Answer on StackOverflow that shows how to get the day of the year from the date.
- Answer to the same question that shows how to go from the day of the year back to the date.