Datetime Get Previous Month Python

Using the datetime module in Python, you can quickly and efficiently extract the previous month from a given date. The term “previous month” is used to refer to the month preceding the one being discussed. As a result, you may say something like “It rained a lot in March, but not as much as it did the month before,” referring to February. Read this guide to retrieve the previous month in Python. You’ll learn how to retrieve the previous month from a date in Python in this post.

What is the DateTime Module in Python?

Even though date and time are not data types in Python, a commonly used module named datetime is commonly used to work with both the date and time. The Python Datetime module is included with Python, thus there’s no need to install it separately.

The Python Datetime module comprises classes that can be utilized to employ time and date. In Python, a date and a datetime are both objects. You’re changing objects rather than timestamps or strings when you try to change these classes.

The DateTime module is divided into six categories:

  1. date – An assumed date that the present Gregorian calendar has always been in effect and will continue to be so. Its characteristics include year, month, and day.
  2. time – A time that is independent of any specific day and implies that each day has exactly 24*60*60 seconds. Its attributes include hour, minute, second, microsecond, as well as tzinfo.
  3. datetime – In conjunction to the date and time, this property includes the month, year, day, minute, hour, microsecond, second, and tzinfo characteristics.
  4. timedelta – A duration that expresses the difference in microseconds between two dates, times, or datetime instances.
  5. tzinfo – It provides objects. These objects include information about the time zone.
  6. timezone – The tzinfo abstract base class’s version has a constant offset from UTC. It is new in version 3.2.

Let’s look at some Python programming examples of how to get a previous month.

Example 1:

The datetime module was imported first in the first example. Datetime is a pre-installed package of Python. It includes classes for handling dates and times. Datetime will provide us with all of the tools we need to find the start day of the preceding month. After importing the module, we must use to generate a date representation (year, month, day).

Then, using abc.replace(…), we can update the date. However, we must take into account the month and year, as well as the month in which the date occurs. To do so, read the code below:

from datetime import date
abc = date(2022, 4, 2)
month, year = (abc.month-1, abc.year) if abc.month != 1 else (12, abc.year-1)
pre_month = abc.replace(day=1, month=month, year=year)

You can see that the previous month’s date is displayed here.

Example 2:

To get a datetime representing a month ago, we’ll use dd.datetime.replace() in this example. The datetime module is imported using the extension dd. Getting a dd.datetime from a month ago yields a new dd.datetime with the date and time from that month. If the current month’s day exceeds the previous month’s number of days, the previous month’s last day will be returned.

In order to acquire the current date and time, we used To get the month of the previous result dd.datetime, use dd.datetime.month. Call datetime.datetime if the current month is 1. t as dd.datetime.year – 1, where dd.datetime is the current date and time, replace(year=t, month=12) with t as dd.datetime.year – 1. Otherwise, set the ‘days’ variable to 0. The number of days since the current day is represented by the variable ‘days’ in the code.

After that, we used the while True syntax to build a loop. A try and except block have been added to the loop. Call dd.datetime in the try block. Replace (month=t.month, with the current month minus one and the current day minus ‘days’.

Use break in order to get out of the loop. A ValueError will be generated if today’s day is larger than the end day of the previous month and the function will jump to the except block. Add 1 to ‘days’ in the except block.

import datetime as dd
t =
if t.month == 1:
   pre_month = t.replace(year=t.year - 1, month=12)
    days = 0
    while True:
            pre_month = t.replace(month=t.month - 1, - days)
        except ValueError:
           days += 1

The above code generated the output that looks something like this.

Example 3:

We’ll employ the replace() and timedelta() methods in this example. We’ll extract the following month, then subtract the day of the next month’s object from the following month, resulting in 1 day before the beginning of the current month, (i.e., the current month’s last date.)

The whole Python code to explain how to retrieve the month’s last date by using replace() + timedelta() methods is shown below.

To begin, we imported the module, set the date, and printed the original date for the readers. After that, we have acquired the following month by using replace() method to get the previous day and offset to get the following month. Then we deducted the days from the following days to get the current month’s end date. Finally, the month’s last date is presented.

import datetime as dd
date = dd.datetime(2022, 4, 2)         
print("Here is the original date: " + str(date))
nxt_date = date.replace(day=28) + dd.timedelta(days=4)
res = nxt_date - dd.timedelta(
print("Here is the last date of month: " + str(

The original and last date of the month is shown here.


In this post, we looked at how to use the datetime module to acquire the prior month’s date. The Python datetime module is demonstrated in detail requirement to obtain the prior month’s date. We’ve given a variety of examples employing various functions such as replace() and timedelta() that you may use to better comprehend the concept.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content