Get the day from a date in Pandas


Pandas is a popular Python library that is used for data analysis and manipulation. Dealing with date and time is a common task while working with data analysis and manipulation in Python Pandas. Getting the day from a given date is a real-life task that might have come across many developers. This task is made easier by a number of functions and methods offered by Pandas. Knowing how to get the day from a date can be very helpful in many cases. In this article, we'll look at several methods for determining the day of the week in Pandas. You should have a solid understanding of using Pandas to extract the day of the week from a date in your project by the end of this article.

The approaches that can be used to complete the task are mentioned below:

Approaches

  • Using dt.dayofweek

  • Using pd.to_datetime() and dt.day_name()

  • Using pd.to_datetime() and dt.day_name() on multiple date strings

  • Using pd.dayofweek and dt.strftime() on multiple date strings

Now let's discuss each approach and how they can be used for getting the day from a date in Pandas.

Method 1: Using dt.dayofweek

We can use the dt.dayofweek property for converting the given date to its particular day of the week and then converting it into its string form by making a manual map.

Algorithm

  • Import the necessary libraries

  • Create a date range object using the pd.date_range() function, providing it the start and end dates.

  • Create a DataFrame with the date range object

  • Add a new column to the DataFrame to store the day of the week

  • Use the dt.dayofweek attribute to get the day of the week from each date stored in the DataFrame

  • Map the day of the week number to its name using the map() method providing it a dictionary.

  • Print the resulting DataFrame.

Step 1 − create a date range

dates = pd.date_range(start='2022-01-01', end='2022-01-07')

Step 2 − create a Dataframe with the date range

df = pd.DataFrame({'date': dates})

Step 3 − add a column with the day of the week

df['day_of_week'] = df['date'].dt.dayofweek

Step 4 − map the day of the week number to its name

df['day_of_week'] = df['day_of_week'].map({
    0: 'Monday',
    1: 'Tuesday',
    2: 'Wednesday',
    3: 'Thursday',
    4: 'Friday',
    5: 'Saturday',
    6: 'Sunday'
})

Step 5 − print the output

print(df.head())

Example

import pandas as pd

# create a date range
dates = pd.date_range(start='2022-01-01', end='2022-01-07')

# create a DataFrame with the dates
df = pd.DataFrame({'date': dates})

# add a column with the day of the week
df['day_of_week'] = df['date'].dt.dayofweek

# map the day of the week number to its name
df['day_of_week'] = df['day_of_week'].map({
    0: 'Monday',
    1: 'Tuesday',
    2: 'Wednesday',
    3: 'Thursday',
    4: 'Friday',
    5: 'Saturday',
    6: 'Sunday'
})

# print the output
print(df.head())

Output

   date      day_of_week
0 2022-01-01    Saturday
1 2022-01-02      Sunday
2 2022-01-03      Monday
3 2022-01-04     Tuesday
4 2022-01-05   Wednesday

Method 2: Using pd.to_datetime() and dt.day_name()

We can use dt.datetime() to first convert a dataframe date to a date_time object and then get the day of the week from that date_time object.

Algorithm

  • Import the pandas library

  • Create a DataFrame with a date string

  • Convert the date string to the corresponding datetime object using the pd.to_datetime() function

  • Add a new column to the DataFrame to store the day of the week

  • Use the dt.day_name() attribute to get the corresponding name of the day of the week from the datetime object

  • Print the resulting DataFrame to get the output.

Example

# Import the pandas library
import pandas as pd

# Create a DataFrame with a single date string
date_obj = pd.DataFrame({'Date': ['2023-04-10']})

# Convert the date string to a datetime object using the to_datetime() function
date_obj['Date'] = pd.to_datetime(date_obj['Date'])

# Add a new column to the DataFrame to store the day of the week
date_obj['Day'] = date_obj['Date'].dt.day_name()

# Print the resulting DataFrame
print(date_obj)

Output

        Date     Day
0 2023-04-10  Monday

Method 3: Using pd.to_datetime() and dt.day_name() on multiple date strings

We can use dt.datetime() to first convert a dataframe date to a date_time object and then get the day of the week from that date_time object.

Algorithm

  • Import the pandas library

  • Create a DataFrame with multiple date strings as the input dates.

  • Convert the date strings to their corresponding datetime objects using the pd.to_datetime() function

  • Add a new column to the DataFrame to store the day of the week

  • Use the dt.day_name() property to extract the name of the day of the week from each datetime object in the DataFrame.

  • Print the resulting DataFrame to get the output.

Example

# Import the pandas library
import pandas as pd

# Create a DataFrame with multiple date strings
dates = pd.DataFrame({'Date':['2019-03-07', '2020-03-07',
   '2021-03-07', '2022-03-07',
   '2023-03-07']})

# Convert the date strings to datetime objects using the pd.to_datetime() function
dates['Date'] = pd.to_datetime(dates['Date'])

# Add a new column to the DataFrame to store the day of the week
dates['Day'] = dates['Date'].dt.day_name()

# Print the resulting DataFrame 
print(dates)

Output

        Date       Day
0 2019-03-07  Thursday
1 2020-03-07  Saturday
2 2021-03-07    Sunday
3 2022-03-07    Monday
4 2023-03-07   Tuesday

Method 4: Using pd.dayofweek and dt.strftime() on multiple date strings

In this method, we are using the dayofweek attribute for getting the day number of date strings and then we are using strftime() function to stringify and abbreviate the name of the weekday.

  • Import the pandas library

  • Create a DataFrame with a single date string

  • Convert the date string to a datetime object

  • Add a new column to the DataFrame to store the day of the week as a numeric value

  • Add a new column to the DataFrame to store the abbreviated name of the day of the week

  • Print the resulting DataFrame

Example

import pandas as pd

# Create a DataFrame with a single date string
date_obj = pd.DataFrame({'Date':['2023-04-10']})

# Convert the date string to a datetime object
date_obj['Date'] = pd.to_datetime(date_obj['Date'])

# Add a new column to the DataFrame to store the day of the week as a number
date_obj['DayNumber'] = date_obj['Date'].dt.dayofweek

# Add a new column to the DataFrame to store the abbreviated name of the day of the week
date_obj['DayOfWeek'] = date_obj['Date'].dt.strftime('%a')

# Print the resulting Dataframe
print(date_obj)

Output

        Date  DayNumber DayOfWeek
0 2023-04-10          0       Mon

Conclusion

By using these approaches, we can also easily add new columns to the DataFrame to store the day of the week and more date-related information in that DataFrame.

Each approach has its own advantages and disadvantages based on the method or function used. You can choose the method you want based on the complexity of the expression you want to have and your personal preference for writing the code.

Updated on: 29-May-2023

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements