Write a program in Python to print the day of the year in a given date series

When working with date data in Pandas, you can extract the day of the year (1-366) from a date series using the dt.dayofyear accessor. This is useful for analyzing seasonal patterns or calculating time differences.

Creating a Date Series

First, let's create a date series using pd.date_range() to generate consecutive dates ?

import pandas as pd

# Create a date range starting from 2020-01-10 with 5 periods
date_range = pd.date_range('2020-01-10', periods=5)
date_series = pd.Series(date_range)
print("Date Series:")
print(date_series)
Date Series:
0   2020-01-10
1   2020-01-11
2   2020-01-12
3   2020-01-13
4   2020-01-14
dtype: datetime64[ns]

Extracting Day of Year

Use the dt.dayofyear accessor to get the day number (1-366) for each date ?

import pandas as pd

date_range = pd.date_range('2020-01-10', periods=5)
date_series = pd.Series(date_range)

# Extract day of year using dt.dayofyear
day_of_year = date_series.dt.dayofyear
print("Day of Year:")
print(day_of_year)
Day of Year:
0    10
1    11
2    12
3    13
4    14
dtype: int64

Example with Different Months

Let's see how it works with dates from different months ?

import pandas as pd

# Create dates spanning different months
dates = ['2020-01-15', '2020-03-01', '2020-07-04', '2020-12-31']
date_series = pd.Series(pd.to_datetime(dates))

print("Dates and their day of year:")
for i, date in enumerate(date_series):
    day_num = date.dayofyear
    print(f"{date.strftime('%Y-%m-%d')}: Day {day_num}")
Dates and their day of year:
2020-01-15: Day 15
2020-03-01: Day 61
2020-07-04: Day 186
2020-12-31: Day 366

Key Points

  • dt.dayofyear returns values from 1 to 365 (or 366 in leap years)

  • January 1st is always day 1, December 31st is day 365/366

  • Works with any pandas Series containing datetime objects

  • Useful for seasonal analysis and time-based calculations

Conclusion

The dt.dayofyear accessor provides an easy way to extract the ordinal day from date series in Pandas. This is particularly useful for seasonal analysis and date arithmetic operations.

Updated on: 2026-03-25T15:52:49+05:30

403 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements