Converting A Date To Day of the Year In Python

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

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


date = datetime(YEAR, JANUARY, 1) + timedelta(DAY_OF_YEAR - 1)