How to Dynamically get the Last Day of the Month in Python

Using pandas and the datetime module, you can dynamically get the last day of the month.

To get the last day of the month, you use a combination of dt.datetime.now() and pd.date_range() function as follows:

import pandas as pd
import datetime as dt

pd.date_range(f"{dt.datetime.now().year}-01-01", f"{dt.datetime.now().year}-12-31" , freq="M")[dt.datetime.now().month-1]

Final Thoughts

Check out more Python tricks in this Colab Notebook or in my recent Python Posts.

Thanks for reading!


Posted

in

by

Tags: