Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 524
Carlos Eduardo Bilar Rodrigues Avatar asked Jun 12 '26 13:06

Carlos Eduardo Bilar Rodrigues


2 Answers

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

like image 170
Neriko Avatar answered Jun 15 '26 03:06

Neriko


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)
like image 43
逆さま Avatar answered Jun 15 '26 01:06

逆さま



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!