Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@moosetraveller
Last active October 20, 2021 22:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moosetraveller/3ebed1c27aa53b24d4b799326c43dae9 to your computer and use it in GitHub Desktop.
Save moosetraveller/3ebed1c27aa53b24d4b799326c43dae9 to your computer and use it in GitHub Desktop.
How to get the first day of the previous month using Python?

How to get the first day of the previous month using Python?

Using datetime

from datetime import date

d = date(2019, 1, 8)  # date.today()

month, year = (d.month-1, d.year) if d.month != 1 else (12, d.year-1)

last_month = d.replace(day=1, month=month, year=year)

print(last_month)  # 2018-12-01

Using datetime and timedelta

from datetime import date
from datetime import timedelta

d = date(2019, 1, 8)  # date.today()

last_month = (d - timedelta(days=d.day)).replace(day=1)

print(last_month)  # 2018-12-01

Using dateutil

from datetime import date
from dateutil.relativedelta import relativedelta

d = date(2019, 1, 8)  # date.today()

last_month = d.replace(day=1) - relativedelta(months=1)

print(last_month)  # 2018-12-01

Using arrow

import arrow

d = arrow.get(2019, 1, 8)  # arrow.now()

last_month = d.shift(months=-1).replace(day=1).datetime.date()

print(last_month)  # 2018-12-01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment