Creating Time Range in Python: Date Range and Month Range

Photo by Mike on Pexels.com

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 date_range() or period_range().

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"

Using date_range()

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
Your output should look like this. There are 366 dates generated.

Using period_range()

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.

months.strftime("%B %Y")

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 Y.

min_year = "1995"
max_year = "2021"

years = pd.period_range(min_year, max_year, freq='Y')
years

You can read more about date_range() and period_range() in the Pandas’s official docs.

We have reached the end of this article. I hope you learn something useful here. Thanks for reading.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s