Subtract 1 year from datetime
Asked Answered
B

2

13

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?

Borges answered 30/4, 2010 at 9:28 Comment(0)
P
61
DateTime.Now.AddYears(-1)

From the documentation:

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

Pelligrini answered 30/4, 2010 at 9:30 Comment(3)
its always the simple things :)Borges
Believe it: it's simply this. A simple solution for a simple problem... a programmer's dream.Mok
It also simplifies age checks (though not getting a calculation of age), because you can test for DateTime.Now.AddYears(-18) > birthDate, for example.Bevis
L
0
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

Legislate answered 25/4, 2021 at 3:44 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.