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? django django

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


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 relativedeltaimport datetimeyears_ago = datetime.datetime.now() - relativedelta(years=5)

Then simply update the date field as others have shown here.


Use timedelta. Something like this should do the trick:

import datetimeyears = 100days_per_year = 365.24hundred_years_later = my_object.date + datetime.timedelta(days=(years*days_per_year))


The .update() method on a Django query set allows you update all values without retrieving the object from the database. You can refer to the existing value using an F() object.

Unfortunately Python's timedelta doesn't work with years, so you'll have to work out 100 years expressed in days (it's 36524.25):

MyModel.objects.update(timestamp=F('timestamp')+timedelta(days=36524.25))