how to subtract months from date in python?

what's the best way to subtract months from a date?

for example I get the following date 20220201 and I need 20220101 to be returned, I tried the following:

from dateutil.relativedelta import relativedelta
month_a= str(datetime.strptime(date, '%Y%m%d') - relativedelta(months=1))

but the return is 2022-01-01, can you help me?

Upvotes: 2

Views: 3918

Answers (2)

wkl
wkl

Reputation: 79921

The standard str representation of a date object is the format %Y-%m-%d (see note) so you need to format it correctly.

#!/usr/bin/env python3

from datetime import date

from dateutil.relativedelta import relativedelta

d = date(2022, 2, 1)
last_month = d - relativedelta(months=1)

# need to specify %Y%m%d as your output format
print(last_month.strftime("%Y%m%d"))

And this outputs

#> python3 date_script.py
2022-01-01

Note - strictly speaking, str on a datetime.date is generated by date.isoformat, which returns the equivalent of %Y-%m-%d.

def isoformat(self):
        """Return the date formatted according to ISO.

        This is 'YYYY-MM-DD'.

        References:
        - http://www.w3.org/TR/NOTE-datetime
        - http://www.cl.cam.ac.uk/~mgk25/iso-time.html
        """
        return "%04d-%02d-%02d" % (self._year, self._month, self._day)

Upvotes: 4

Neriko
Neriko

Reputation: 60

Try

month_a = datetime.strftime(datetime.strptime(date, '%Y%m%d') - relativedelta(months=1), '%Y%m%d')

strftime is a tool to convert date to a string with desired format

Upvotes: 4

Related Questions