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

kelvinfix picture kelvinfix · May 3, 2011 · Viewed 56.6k times · Source

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.

Answer

Max picture Max · May 3, 2011

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.