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

前提是你 提交于 2019-11-29 04:43:41

问题


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.


回答1:


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.




回答2:


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



回答3:


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



回答4:


When you get the value of a Django datetime field from the database, it comes in the form of a Python datetime object.

I think the easiest way to add 100 years to a Python datetime object is like this:

from datetime import datetime

d = datetime_object_from_database

d_plus_100_years = datetime(d.year + 100, *d.timetuple()[1:-2])

Then save that back to the database. As noted in the comments though, this will fail utterly if the date is a leap day in a year that’s a multiple of 400.




回答5:


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


来源:https://stackoverflow.com/questions/5871168/how-can-i-subtract-or-add-100-years-to-a-datetime-field-in-the-database-in-djang

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!