Table of Contents
Use pandas.period_range() Method
To get the list of months between two specified dates in Python:
- Use pandas’s
period_range()to get list of months between start date and end date withfreq='M'. - Use list comprehension to iterate over list of months.
- For each month, use
strftime()method to convert it in appropriate format.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
import pandas as pd start_date, end_date = "2021-10-10", "2022-02-08" month_list = pd.period_range(start=start_date, end=end_date, freq='M') month_list = [month.strftime("%b-%Y") for month in month_list] print(f"Months that lie between '{start_date}' and '{end_date}' are: ") print(*month_list, sep=", ") print(f"Total months: {len(month_list)}") |
The execution of the above program will print the following on the console.
|
1 2 3 4 5 |
Months that lie between '2021-10-10' and '2022-02-08' are: Oct-2021, Nov-2021, Dec-2021, Jan-2022, Feb-2022 Total months: 5 |
The pandas library is a powerful data analysis and manipulation tool for Python. It provides data structures and operations for manipulating numerical tables and time series.
It supports high-level data structures and functions for working with relational or labelled data. The pandas library provides the pd.period_range() method that creates a TimeSeries object from a date range and returns a tuple of the days between two dates.
It holds start, end, period, and freq as arguments. Of the three parameters: start, end, and period, exactly two must be specified; otherwise, the method will return a ValueError.
We used pd.period_range() to find the months between start_date and end_date by providing the Month end frequency M as an offset alias to the freq.
The strftime() function in Python formats date and time objects into strings according to the specified format. It is a part of the datetime module, which provides various functions for working with dates and times.
Once we got the month_list, we used list comprehension to apply the strftime() method to format every month of month_list using %b-%Y as format codes. There are many other format codes documented.
To print every month in month_list, we provided the print() method with sep=", " to the print statement to print the list separated by a comma.
Further reading:
Use Nested List Comprehension
To get the list of months between two dates in Python:
- Use the
datetime.strptime()method to convert start and end date to appropriate format. - Use the
forloop to iterateyearthat lies in the range of start date’s year and end date’s year. - Use an inner
forloop to iterate everymonththat lies in the belowrange(). - In the
range()function, set thestarttostart date's monthifyearequalsstart date's year; otherwise set it to1. - In the
range()function, set theendto(end date's month)+1ifyearequalsend date's year; otherwise set it to13.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
from datetime import datetime dates = ["2021-10-10", "2022-02-08"] start_date, end_date = [datetime.strptime(_, "%Y-%m-%d") for _ in dates] month_list = [datetime.strptime('%2.2d-%2.2d' % (year, month), '%Y-%m').strftime('%b-%Y') for year in range(start_date.year, end_date.year+1) for month in range(start_date.month if year == start_date.year else 1, end_date.month+1 if year == end_date.year else 13)] print(f"Months that lie between '{dates[0]}' and '{dates[1]}' are: ") print(*month_list, sep=", ") print(f"Total months: {len(month_list)}") |
On the successful execution of the above code, we will get the following output.
|
1 2 3 4 5 |
Months that lie between '2021-10-10' and '2022-02-08' are: Oct-2021, Nov-2021, Dec-2021, Jan-2022, Feb-2022 Total months: 5 |
The datetime module in Python provides classes for manipulating dates and times easily. From this module, we imported the datetime class.
The strptime() function of datetime parses a string and interprets it as a date and time in a specified format. We applied it on every date in dates to get formatted start_date and end_date.
We used the for loop to iterate every year lying in the range start_date.year and end_date.year. The loop creates a formatted month_list using strptime() and strftime() functions which we discussed earlier.
We used an inner for loop to iterate both dates concerning their months. In that loop, we used the range() function as:
- We set the
starttostart_date.monthifyearequalsstart_date.year; otherwise, the program jumped theelsepart to set it to1. - We set the
endtostart_date.month+1ifyearequalsend_date.year; otherwise, the program jumped theelsepart to set it to13.
Printing is the same as we discussed while explaining the code snippet using the pandas.period_range() method.