When creating business reports or running queries against a database or web analytics platform in a business setting, you’ll often need to know the start and end dates of the month.
In this quick project, we’ll create a couple of functions that will help us calculate the start and end dates of the month, so you can pass the values to your queries to extract the correct data.
First, open a Jupyter notebook and import the packages we’ll need. We can use three modules from the Python standard datetime
library for this: date
, datetime
, and timedelta
.
from datetime import date, datetime, timedelta
Next, we’ll create a function to return the start date of the month in the common YYYY-MM-DD date format used in databases such as MySQL. To do this, we’ll pass in the year
and month
as integers, and then return a datetime
object by setting the day to 1.
We’ll then convert the datetime
object to a string in the format YYYY-MM-DD
using strftime()
.
def get_first_date_of_current_month(year, month):
"""Return the first date of the month.
Args:
year (int): Year
month (int): Month
Returns:
date (datetime): First date of the current month
"""
first_date = datetime(year, month, 1)
return first_date.strftime("%Y-%m-%d")
Now we can run the get_first_date_of_current_month()
function to get the first date of the current month, simply by passing in the year and month.
first = get_first_date_of_current_month(2022, 1)
first
'2022-01-01'
first = get_first_date_of_current_month(2025, 5)
first
'2025-05-01'
Calculating the month end date is a bit harder, since unlike the first day of the month, which is always a 1, the last date on the month could be a 31, 30, 28, or 29 depending on the month or year.
There are a few ways to do this, but I’ve gone with the following: last_date = datetime(year, month + 1, 1) + timedelta(days=-1)
.
This will calculate the first date of the following month, then subtract 1 day from it to get the last date of the current month. The timedelta
module is excellent for calculating the difference between dates.
def get_last_date_of_month(year, month):
"""Return the last date of the month.
Args:
year (int): Year, i.e. 2022
month (int): Month, i.e. 1 for January
Returns:
date (datetime): Last date of the current month
"""
if month == 12:
last_date = datetime(year, month, 31)
else:
last_date = datetime(year, month + 1, 1) + timedelta(days=-1)
return last_date.strftime("%Y-%m-%d")
last = get_last_date_of_month(2022, 1)
last
'2022-01-31'
last = get_last_date_of_month(2022, 4)
last
'2022-04-30'
Thanks to Ron Burak for a correction.
Matt Clarke, Friday, March 18, 2022