How to subtract a month from an specific date format?

Viewed 111

I am trying to set a function that subtracts a month from an specific date format as an argument, and returns a date in the same specific date format,

This argument is given by today's month and year: 01/%m/%Y.

Actual code:

from datetime import datetime
import dateutil.relativedelta

actual_date = datetime.now()
actual_date = "{}/{}/{}".format('01', actual_date.month, actual_date.year)


def set_date(actual_date):
    print(actual_date - dateutil.relativedelta.relativedelta(months=1))

Here's the output when set_date() is tested:

set_date(actual_date)

TypeError: unsupported operand type(s) for -: 'str' and 'relativedelta'

Expected output should look like this:

01/12/2020
2 Answers

You're doing it in the wrong order. Perform the date calculation first, and then convert to a string.

now = datetime.now()
one_month_ago = now - dateutil.relativedelta.relativedelta(months=1)
print("{}/{}/{}".format('01', one_month_ago.month, one_month_ago.year))

In the first line, you get a datetime, then in the second line you build a string out of it. As a result, in set_date you get the mentioned error.

I suggest that you remove the second line and simply give the datetime object to set_date and do a strftime on the result:

actual_date = datetime.now()

def set_date(actual_date):
    result = actual_date - dateutil.relativedelta.relativedelta(months=1)
    print(datetime.strftime(result, "01/%m/%Y"))

However, if you really want to keep those conversions, you can use strptime for that purpose.

actual_date = datetime.now()
actual_date = datetime.strptime("{}/{}/{}".format('01', actual_date.month, actual_date.year), "%d/%m/%Y")


def set_date(actual_date):
    result = actual_date - dateutil.relativedelta.relativedelta(months=1)
    print(datetime.strftime(result, "%d/%m/%Y"))
Related