How to Extract Day Number of the Year from a Date in Python?

In this tutorial, I will explain how to extract the day number of the year from a date in Python. Someone asked this question during a Python webinar and I explored more about this topic I will share my findings in this article, and I will help you to understand this topic by giving examples and by adding screenshots of executed example codes.

Use the datetime Module

Python’s datetime module provides a range of functions to manipulate dates and times. To extract the day number of the year, we can use the timetuple method of a datetime object. This method returns a time.struct_time object, from which we can access the tm_yday attribute.

Example 1: Basic Extraction

Let’s start with a simple example. Suppose we have a date, and we want to find out its day number of the year.

from datetime import datetime

# Define a date
date = datetime(2024, 11, 13)

# Extract the day number of the year
day_of_year = date.timetuple().tm_yday

print(f"The day number of the year for {date.strftime('%Y-%m-%d')} is {day_of_year}.")

This code will output:

The day number of the year for 2024-11-13 is 318.

I have executed the above example and added the screenshot below.

Day Number of the Year from a Date in Python

Read Difference Between Class and Instance Variables in Python

Example 2: Handle User Input

In a real-world scenario, you might want to handle user input. For example, let’s create a script that prompts the user to enter a date and then displays the day number of the year.

from datetime import datetime

# Prompt the user to enter a date
date_input = input("Enter a date (YYYY-MM-DD): ")
date = datetime.strptime(date_input, "%Y-%m-%d")

# Extract the day number of the year
day_of_year = date.timetuple().tm_yday

print(f"The day number of the year for {date.strftime('%Y-%m-%d')} is {day_of_year}.")

Output:

Enter a date (YYYY-MM-DD):

I have executed the above example and added the screenshot below.

How to Extract Day Number of the Year from a Date in Python

Check out How to Validate Passwords in Python?

Example 3: Work with Pandas

If you are working with large datasets, you might use the Pandas library. Pandas allow for efficient data manipulation and analysis. Let’s see how to extract the day number of the year from a date column in a Pandas DataFrame.

First, install Pandas if you haven’t already:

pip install pandas

Now, let’s create a DataFrame and extract the day number of the year.

import pandas as pd

# Create a sample DataFrame
data = {
    'date': ['2024-01-01', '2024-07-04', '2024-12-31']
}
df = pd.DataFrame(data)

# Convert the 'date' column to datetime
df['date'] = pd.to_datetime(df['date'])

# Extract the day number of the year
df['day_of_year'] = df['date'].dt.dayofyear

print(df)

This code will output:

        date  day_of_year
0 2024-01-01            1
1 2024-07-04          186
2 2024-12-31          366

I have executed the above example and added the screenshot below.

Day Number of the Year from a Date in Python Work with Pandas

Read How to Validate Email Addresses in Python?

Example 4: Handle Leap Years

Leap years can be tricky when working with dates. Python’s datetime module handles leap years automatically. Let’s see an example that includes a leap year.

from datetime import datetime

# Define a leap year date
leap_year_date = datetime(2024, 2, 29)

# Extract the day number of the year
day_of_year = leap_year_date.timetuple().tm_yday

print(f"The day number of the year for {leap_year_date.strftime('%Y-%m-%d')} is {day_of_year}.")

This code will output:

The day number of the year for 2024-02-29 is 60.

Check out How to Use the round() Function in Python?

Example 5: Create a Function

To make your code reusable, you can create a function that takes a date as input and returns the day number of the year.

from datetime import datetime

def get_day_of_year(date_str):
    date = datetime.strptime(date_str, "%Y-%m-%d")
    return date.timetuple().tm_yday

# Test the function
print(get_day_of_year("2024-11-13"))
print(get_day_of_year("2024-07-04"))

Output:

318
186

Read How to Use the Floor() Function in Python?

Conclusion

In this tutorial, I explained how to extract the day number of the year from a date in Python. We explored various methods to extract the day number of the year from a date by using datetime module, We discussed basic extraction, handling user input, working with pandas, handling leap year, and creating a function.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.