substracting datetime object on date level

Viewed 30

All answers require hour, min, s, etc... like this:

from datetime import datetime
datetime.today() - datetime.timedelta(days=1)

I don't want to create datetime object that contain all hours, minutes, seconds, etc...

Is there a way to add and substract date on higher level(date?)

What I desire:

dt = "20210601"
st_date = dt - 30days
print(st_date)
>>> "2021-05-02"

What I tried:

datetime.strptime("20210601", "%Y%m%d") - datetime.timedelta(days=30)

Outputs AttributeError: type object 'datetime.datetime' has no attribute 'timedelta' which I assume it wants all hours, mins, seconds, etc...

1 Answers

Try using the timedelta function instead of the datetime.timedelta function:

from datetime import datetime, timedelta
stdate = datetime.strptime("20210601", "%Y%m%d") - timedelta(days=30)
print(stdate)

Output:

2021-05-02 00:00:00
Related