Write a Python program to convert Year/Month/Day to Day of Year


This program calculates the day of the year (doy) for the current date using the datetime module of Python. First, it gets the current date and time using the datetime.now() method of the datetime module and stores it in the today variable.

Next, it calculates the number of days between the current date and the first day of the year using the difference between the current date and a new datetime object initialized with the year, month and day set to January 1 of the same year as the current date. The days attribute of the timedelta object obtained from the difference between the two dates is then extracted and one is added to it to get the day of the year. Finally, it prints the calculated day of the year to the console using the print() function.

Source Code

import datetime
today = datetime.datetime.now()
doy = (today - datetime.datetime(today.year, 1, 1)).days + 1
print(doy)

Output

267

Example Programs