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?
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With