The Wayback Machine - https://web.archive.org/web/20240807004457/https://www.geeksforgeeks.org/extract-week-number-from-date-in-pandas-python/
Open In App

Extract week number from date in Pandas-Python

Last Updated : 23 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Many times, when working with some data containing dates we may need to extract the week number from a particular date. In Python, it can be easily done with the help of pandas. Example 1: 

Python3




# importing pandas as pd
import pandas as pd
 
# creating a dictionary containing a date
dict = {'Date':["2015-06-17"]}
 
# converting the dictionary to a dataframe
df = pd.DataFrame.from_dict(dict)
 
# converting the date to the required format
df['Date'] = pd.to_datetime(df['Date'], errors ='coerce')
df.astype('int64').dtypes
 
# extracting the week from the date
weekNumber = df['Date'].dt.week
 
print(weekNumber)


Output:

0    25
Name: Date, dtype: int64

Example 2: We can also do the same for multiple dates by adding more dates in the ‘Date’ object. 

Python3




# importing pandas as pd
import pandas as pd
 
# creating a dictionary containing a date
dict = {'Date':["2020-06-17", "2020-01-14",
                "2020-09-20", "2020-08-15"]}
 
# converting the dictionary to a
# dataframe
df = pd.DataFrame.from_dict(dict)
 
# converting the date to the required
# format
df['Date'] = pd.to_datetime(df['Date'],
                            errors ='coerce')
df.astype('int64').dtypes
 
# extracting the week from the date
weekNumber = df['Date'].dt.week
 
print(weekNumber)


Output: python-extract-week-number Example 3: Extracting week number from dates for multiple dates using date_range() and to_series().

  • pandas.data_range(): It generates all the dates from the start to end date Syntax:

pandas.date_range(start, end, periods, freq, tz, normalize, name, closed)

  • pandas.to_series(): It creates a Series with both index and values equal to the index keys. Syntax:
Index.to_series(self, index, name)

Python3




# importing pandas as pd
import pandas as pd
 
# generating all dates in given range
# with increment by days
allDates = pd.date_range('2020-06-27', '2020-08-03', freq ='W')
 
# converting dates to series
series = allDates.to_series()
 
series.dt.week


Output: pandas-extract-week-number-2 Example 4: In this example, we’ll be using pandas.Series() to generate dates and use a different way to convert the series to the dataframe. pandas.Series(): Used to create a one-dimensional array with axis labels. Syntax:

pandas.Series(data, index, dtype, name, copy, fastpath)

Python3




# importing pandas as pd
import pandas as pd
 
# generating the series
dates = pd.Series(pd.date_range('2020-2-10',
                                periods = 5,
                                freq ='M'))
 
# converting to dataframe
df = pd.DataFrame({'date_given': dates})
 
# extracting the week number
df['week_number'] = df['date_given'].dt.week
 
df


Output: pandas-extract-week-number-5



Similar Reads

Pandas Series dt.week | Extract Week Number from DateTime Series
Pandas dt.week attribute returns a NumPy array containing the week ordinal of the year in the underlying data of the given DateTime Series object. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']
2 min read
Pandas Series dt.date | Extract Date From DateTime Objects
The dt.date attribute extracts the date part of the DateTime objects in a Pandas Series. It returns the NumPy array of Python datetime.date objects, mainly the date part of timestamps without information about the time and timezone. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '201
2 min read
Pandas Series dt.weekday | Find Day of the Week in Pandas
The dt.weekday attribute returns the day of the week. It is assumed the week starts on Monday, which is denoted by 0, and ends on Sunday which is denoted by 6. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day
2 min read
Pandas Series dt.weekofyear Method | Get Week of Year in Pandas Series
The dt.weekofyear attribute returns a Series containing the week ordinal of the year in the underlying data of the given series object. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index =
2 min read
Pandas Series dt.dayofweek | Get Day of Week from DateTime Series in Pandas
Pandas dt.dayofweek attribute returns the day of the week from the given DateTime Series Object. It is assumed the week starts on Monday, which is denoted by 0, and ends on Sunday which is denoted by 6. Example: C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:
2 min read
Extract date from a specified column of a given Pandas DataFrame using Regex
In this article, we will discuss how to extract only valid date from a specified column of a given Data Frame. The extracted date from the specified column should be in the form of 'mm-dd-yyyy'. Approach: In this article, we have used a regular expression to extract valid date from the specified column of the data frame. Here we used \b(1[0-2]|0[1-
2 min read
How to extract date from Excel file using Pandas?
Prerequisite: Regular Expressions in Python In this article, Let's see how to extract date from the Excel file. Suppose our Excel file looks like below given image then we have to extract the date from the string and store it into a new Dataframe column. For viewing the Excel file Click Here. Approach : Import required module.Import data from Excel
3 min read
How to print date starting from the given date for n number of days using Pandas?
In this article, we will print all the dates starting from the given date for n number days. It can be done using the pandas.date_range() function. This function is used to get a fixed frequency DatetimeIndex. Syntax: pandas.date_range(start=None, end=None, periods=None, freq=None, tz=None, normalize=False, name=None, closed=None, **kwargs) Approac
2 min read
Pandas Series dt.minute | Extract Minute from DateTime Series in Pandas
Pandas Series.dt.minute attribute returns a NumPy array containing the minutes of the DateTime in the underlying data of the given series object. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '2010-4-22 09:25', '2019-11-8 02:22']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']
2 min read
Python | Pandas PeriodIndex.week
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas PeriodIndex.week attribute return an Index object containing the ordinal value of week of each period element for the given Perio
2 min read
Practice Tags :
three90RightbarBannerImg