Python has a module called datetime which has several classes for manipulating date and time.

By using the “timedelta” in datetime module we can easily get the previous month’s date.

Following is the example

  1. Get the current month date.
  2. Replace the day with 1 in the current month, so that we can easily get the previous month’s date by using the timedelta (We are interested in the previous month’s date only).
  3. Get the last month’s date by subtracting the current date – (1-day time delta).
#Importing the datetime module
import datetime

#Getting today's date
todayDate = datetime.date.today()

#Replace the day with "1" and subtract 1 day from the current day
#we will get the last month date
last_month = todayDate.replace(day=1) - datetime.timedelta(days=1)
print(last_month.strftime("%Y%m"))

Categorized in:

Tagged in: