How can I subtract or add 100 years to a datetime
field in the database in Django?
The date is in database, I just want to directly update the field without retrieving it out to calculate and then insert.
The easiest way to subtract years from a date in Python is to use the dateutil extension. The relativedelta object from the dateutil. relativedelta module allows you to subtract any number of years from a date object.
Subtract(TimeSpan) method returns a DateTime value that is later than the date and time of the current instance. The DateTime. Subtract(TimeSpan) method allows you to subtract a time interval that consists of more than one unit of time (such as a given number of hours and a given number of minutes).
Subtraction of two datetime objects in Python:It is allowed to subtract one datetime object from another datetime object. The resultant object from subtraction of two datetime objects is an object of type timedelta.
I would use the relativedelta
function of the dateutil.relativedelta
package, which will give you are more accurate 'n-years ago' calculation:
from dateutil.relativedelta import relativedelta import datetime years_ago = datetime.datetime.now() - relativedelta(years=5)
Then simply update the date
field as others have shown here.
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