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.
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.
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.
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))
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))
relativedate()
instead of timedelta()
if you need that accuracy –
Goldwin F()
objects. The .2425 in the number 365.2425 is the bit that tries to take leap years into account, as much as you can with F()
objects. –
Pecoraro 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
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!
2000-02-29
, for example). –
Tanka The simplest way would be to use dateutil.relativedelta
as mentioned in another answer. However, if you don't want to add an extra dependency on python-dateutil
, it's pretty easy to implement a similar logic using only standard library modules:
from calendar import isleap
from datetime import datetime
def subtract_years(dt, years):
"""Subtract years from a date or datetime."""
year = dt.year - years
# if leap day and the new year is not leap, replace year and day
# otherwise, only replace year
if dt.month == 2 and dt.day == 29 and not isleap(year):
return dt.replace(year=year, day=28)
return dt.replace(year=year)
print(subtract_years(datetime(2023, 10, 26), 100)) # 1923-10-26 00:00:00
print(subtract_years(datetime(2000, 2, 29), 4)) # 1996-02-29 00:00:00
print(subtract_years(datetime(2000, 2, 29), 100)) # 1900-02-28 00:00:00
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)
© 2022 - 2024 — McMap. All rights reserved.