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

PythonDjangoDatetimeDjango Database

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

Use timedelta. Something like this should do the trick:

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

Solution 3 - Python

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

Solution 4 - Python

Though setting the number of days in a year as 365.25 (from (365+365+365+366)/4) perfectly offsets the difference-in-days error, it would sometimes lead to unwanted results as you might cause undesirable changes in attributes other than year, especially when you are adding/subtracting 1 or a few years.

If you want to just change the year while preventing changes in other datetime's attributes, just do the algebra on the year attribute like the following:

from datetime import datetime 

d = my_obj.my_datetime_field

""" subtract 100 years. """
my_obj.my_datetime_field = datetime(d.year-100, d.month, d.day, d.hour, d.minute, d.second, d.microsecond, d.tzinfo)

my_obj.save()

Hope it helps!

Solution 5 - Python

Subtract year from today and use this format. x = datetime.datetime(2020 - 100, 5, 17)

import datetime
datetime.date(datetime.date.today().year - 100, datetime.date.today().month, datetime.date.today().day)

Solution 6 - Python

I Know it's an old question, but I had the problem to find out a good one to solve my problem, I have created this: Use plus(+) or minus(-) to handle with:

import datetime # Don't forget to import it

def subadd_date(date,years):
    ''' Subtract or add Years to a specific date by pre add  + or - '''
    if isinstance(date,datetime.datetime) and isinstance(years,int):
		day,month,year = date.day , date.month , date.year
		#If you want to have HOUR, MINUTE, SECOND 
		#With TIME: 
		# day,month,year,hour,minute,second = date.day, date.month,date.year,date.hour,date.minute,date.second  

		py = year + years # The Past / Futur Year
		new_date_str = "%s-%s-%s" % (day,month,py) # New Complete Date
		# With TIME : new_date_str = "%s-%s-%s %s:%s:%s" % (month,day,py,hour,minute,second)
		try:
			new_date = datetime.datetime.strptime(new_date_str,"%d-%m-%Y")
		except ValueError: # day is out of range for month (February 29th)
			new_date_str = "%s-%s-%s" % (1,month+1,py) # New Complete Date : March 1st
			new_date = datetime.datetime.strptime(new_date_str,"%d-%m-%Y")

		return new_date
		# With TIME : return datetime.datetime.strptime(new_date_str,"%d-%m-%Y %H:%M:%Y")
    return None

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkelvinfixView Question on Stackoverflow
Solution 1 - PythonMaxView Answer on Stackoverflow
Solution 2 - PythonVladimir PrudnikovView Answer on Stackoverflow
Solution 3 - PythonWill HardyView Answer on Stackoverflow
Solution 4 - PythonxemexpressView Answer on Stackoverflow
Solution 5 - PythonPravin LView Answer on Stackoverflow
Solution 6 - PythonLemayzeurView Answer on Stackoverflow