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

后端 未结 5 1053
谎友^
谎友^ 2020-12-25 11:10

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 wit

相关标签:
5条回答
  • 2020-12-25 11:26

    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.

    0 讨论(0)
  • 2020-12-25 11:30

    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
    
    0 讨论(0)
  • 2020-12-25 11:32

    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))
    
    0 讨论(0)
  • 2020-12-25 11:40

    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!

    0 讨论(0)
  • 2020-12-25 11:43

    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))
    
    0 讨论(0)
提交回复
热议问题