How to Quickly and Easily get a List of Week-end, Month-end, or Year-end Dates in Python

Getting month-end, or any other interval can be cumbersome. In this post, I’ll show you how to generate a list of dates quickly in Python.

import pandas as pd
import datetime as dt

#Yesterday's date
pd.date_range(start='1/31/2000', end= dt.datetime.now())[-2]

#Most recent month end date
pd.date_range(start='1/31/2000', end= dt.datetime.now(), freq='M')[-1]

#Most recent quarter end date
pd.date_range(start='1/31/2000', end= dt.datetime.now(), freq='Q')[-1]

#Most recent year end date
pd.date_range(start='1/31/2000', end= dt.datetime.now(), freq='Y')[-1]

Further Explanation

If you have ever tried to get the last month-end date using Python, you probably know that it’s pretty tricky. For example, today is 2020-11-11 and I need to have 2020-10-31 as a variable for filtering and a few other tasks. You could mess around with the DateTime module, but it’s not as straightforward as one would think.

Here is where the Pandas function pd.date_range comes into play. It will generate a list of dates when you pass in a start date, end date, and an optional frequency. There are more arguments you can pass in as well but those three will do the job.

You’ll want to import the pandas and datetime packages.

import pandas as pd
import datetime as dt

Simply passing in a start and an end date and the function will produce a list of dates with a day frequency.

Add in a frequency argument of M and you quickly get a list of month end dates.

You also have the ability to do a weekly frequency and specify the day of the week to group on.

If you notice above, I added in dt.datetime.now() in my end argument. This is a trick to make the list dynamic. When that is entered, the last item in the list is the most frequent ending date in the past. In other words, you won’t have an end date that is greater than the date used in the end argument.

Finally, since the function produces a list, you can apply the [-1] to your list to get the latest date from your list.

Thanks for reading!


Posted

in

by

Tags: