When using Python, there are a number of ways to get the day of the year in Python. The easiest way to use datetime.timetuple() to convert your date object to a time.struct_time object then access ‘tm_yday’ attribute.
import datetime
currentDate = datetime.date.today()
day_of_year = currentDate.timetuple().tm_yday
print(currentDate)
print(day_of_year)
#Output:
2022-03-06
65
You can also get the day of the year using the strftime function passing “%j”.
import datetime
currentDate = datetime.date.today()
print(currentDate)
print(currentDate.strftime("%j"))
#Output:
2022-03-06
065
When working in Python, many times we need to create variables which represent dates and times. When creating and displaying values related to dates, sometimes we need to display a particular day.
With Python, we can easily get the day of the year.
The Python datetime module has many great functions which allow us to interact with date and datetime objects easily.
The easiest way to use datetime.timetuple() to convert your date object to a time.struct_time object then access ‘tm_yday’ attribute.
Below is an example of how to get the day of the year for a date object in Python.
import datetime
currentDate = datetime.date.today()
day_of_year = currentDate.timetuple().tm_yday
print(currentDate)
print(day_of_year)
#Output:
2022-03-06
65
Using strfttime to Remove the Time from Datetime in Python
The Python strftime() function is very useful when working with date and datetime variables. strftime() accepts a string representing the format of a date and returns the date as a string in the given format.
We can use strftime() to easily get the day of the year.
To get the day of the year using strftime(), pass “%j”.
Below is a simple Python example of how to convert a date to the day of the year using strftime().
import datetime
currentDate = datetime.date.today()
print(currentDate)
print(currentDate.strftime("%j"))
#Output:
2022-03-06
065
Hopefully this article has been useful for you to learn how to convert a date to the day of the year in Python using the datetime module.