Oftentimes we run into a problem where we are required to generate a list or series of dates between two available dates.
Pandas has provided us with some functionalities that made this possible using
First, let’s define the two dates we have to generate the dates in between.
import pandas as pd min_date = "2020-01-01" max_date = "2020-12-31"
We are going to generate the dates between the first day of 2020 to the last day of 2020, which means that there should be exactly 366 days (because 2020 is a leap year, remember?).
dates = pd.date_range(min_date, max_date) dates
As an alternative to using
date_range() we can also use
period_range() to generate similar results.
dates = pd.period_range(min_date, max_date, freq='D') dates
As a note, the
freq parameter is optional here. You can still use the code above without this parameter.
Furthermore, you can create a range of months using
period_range(). Here you generate the months between first month and the last month of 2020. I usually like to call these month and year period because you don’t only get the month, but also the year. It’s important when you are dealing with monthly period data from a range of different years.
min_month = "2020-01" max_month = "2020-12" months = pd.period_range(min_month, max_month, freq='M') months
If you want to print the months and year above in a more readable format, you can use
strftime() function. The
%B here is used to get the month full name.
Last but not least is using
period_range() to generate a list of years. It’s similar to the code we have tried above, except now we change the
freq parameter into
min_year = "1995" max_year = "2021" years = pd.period_range(min_year, max_year, freq='Y') years
We have reached the end of this article. I hope you learn something useful here. Thanks for reading.