Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I subtract or add 100 years to a datetime field in the database in Django?

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.

like image 922
kelvinfix Avatar asked May 03 '11 14:05

kelvinfix


People also ask

How do I subtract years from a date in Python?

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.

How do I subtract date from datetime?

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).

Can you subtract two datetime objects?

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.


1 Answers

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.

like image 139
Max Avatar answered Sep 25 '22 11:09

Max