How to get the First Day of the Previous Month in Python
Someone asked me recently how to get the first day of the previous month in Python. There is not just one way. Let me introduce you to four different solutions.
We are going to use three different packages: datetime
(built-in), dateutil
and arrow
.
Using datetime
datetime
is a built-in package providing classes for manipulating dates and times. datetime
will provide us with all necessary features to get the first day of the previous month.
First, we need to create a date representation using datetime.date(year, month, day)
.
Next, we can update the date by using d.replace(...)
. However, we also have to evaluate the month and year, taking into account that the date is in January. Here is an example:
An alternative solution while using datetime.date
as well makes use of datetime.timedelta
.
Instead of evaluating the month represented by d
, we just subtract a timedelta
from d
using d.days
:
Using dateutil.relativedelta
dateutil
is an external Python library providing extensions to the standard datetime
built-in module.
You can simply install dateutil
by using pip install python-dateutil
.
This solution works very similar to our second datetime
solution. The only difference here is that we subtract a relativedelta
of 1
month.
Using arrow
arrow
is an external Python library that offers a more human-readable approach to work with dates, times and timestamps.
You can install arrow
by using pip install arrow
.
We will need to know how to create a date representation d
using arrow
which can be done fairly simple with arrow.get(year, month, day)
:
Again, very similar to our datetime.relativedelta
approach above, we replace the day with the first day of the month and shift the date one month back:
However, there may be a need to convert the result to a datetime.date
object which can be achieved with d.datetime.date()
.
TL;DR find all code examples here.
Addendum on October 20, 2021: Although I came across with this related Stackoverflow question after I wrote this article, I’d like to give some credit to David’s and Jab’s answers. I guess there are only so many variations. ;)