Phil
Phil

Reputation: 1841

Subtract 1 year from datetime

I have seen a lot of info on how to subtract one datetime from the other and how to add years on to a datetime. but the following is giving me a headache....

When a user inserts a record a hidden field called subdate with a value of datetime.now is added to the db.

I then need to have an 'old records' page that lists all the entries that are over 1 year old and was hoping to use something (but using subtract method) similar to;

(DateTime.Now.AddYears(1))

but there is no SubtractYears available? Why?

Please can you let me know how I achieve the same result?

Upvotes: 13

Views: 36918

Answers (2)

lchristij
lchristij

Reputation: 1

now = datetime.now()
last_year = (now.year - 1)
datestr = (datetime.strptime(str(now.year - 1), "%Y")).strftime("%y")
print(f"Last Year: {datestr}")

The output will be:

Last Year: 20

If you prefer to have four digit year then change %y to %Y

Upvotes: 0

Kobi
Kobi

Reputation: 137997

DateTime.Now.AddYears(-1)

From the documentation:

A number of years. The value parameter can be negative or positive.

Upvotes: 61

Related Questions