How to get the Day of Year from a date using Pandas?

Using Pandas, you can get the Day of Year from a date by using the .dt.dayofyear attribute on a pandas datetime object. This will return the day of the year for the given date as an integer. For example, if you have a datetime object called ‘date’, you can use ‘date.dt.dayofyear’ to get the day of the year for that date.


You can use the following basic syntax to get the day of year from a date column in a pandas DataFrame:

df['day_of_year'] = df['date'].dt.dayofyear

This particular example creates a new column called day_of_year that contains the day of the year of the value in the date column.

Note that the values for day_of_year will range from 1 (January 1st) to 365 (December 31st).

The following example shows how to use this syntax in practice.

Example: Get Day of Year from Date in Pandas

Suppose we have the following pandas DataFrame that contains information about the total sales made at some store on various dates:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'date': pd.date_range(start='1/1/2022', freq='M', periods=10),
                   'sales': [6, 8, 10, 5, 4, 8, 8, 3, 5, 14]})

#view DataFrame
print(df)

         date  sales
0  2022-01-31      6
1  2022-02-28      8
2  2022-03-31     10
3  2022-04-30      5
4  2022-05-31      4
5  2022-06-30      8
6  2022-07-31      8
7  2022-08-31      3
8  2022-09-30      5
9  2022-10-31     14

Related:

We can use the following code to create a new column called day_of_year that contains the day of the year from the date column:

#create new column that contains day of year in 'date' column
df['day_of_year'] = df['date'].dt.dayofyear

#view updated DataFrame
print(df)

        date  sales  day_of_year
0 2022-01-31      6           31
1 2022-02-28      8           59
2 2022-03-31     10           90
3 2022-04-30      5          120
4 2022-05-31      4          151
5 2022-06-30      8          181
6 2022-07-31      8          212
7 2022-08-31      3          243
8 2022-09-30      5          273
9 2022-10-31     14          304

The new column called day_of_year contains the day of year from the date column.

It’s worth noting that if you’re working with a leap year, this function will automatically extend the range of possible values from 365 to 366.

Also note that if the column you’re working with is a string column, you must first use pd.to_datetime() to convert the strings to recognizable dates:

#convert string column to datetime and calculate day of year
df['day_of_year'] = pd.to_datetime(df['date']).dt.dayofyear

Note: You can find the complete documentation for the pandas dayofyear function .

x