如何在 Django 数据库中的日期时间字段中减去或加上 100 年?

发布于 2024-11-04 10:30:39 字数 100 浏览 0 评论 0原文

如何在 Django 数据库中的 datetime 字段中减去或加上 100 年?

日期在数据库中,我只想直接更新字段而不检索它来计算然后插入。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

猥琐帝 2024-11-11 10:30:39

我将使用 dateutil.relativedelta 包的 relativedelta 函数,这将为您提供更准确的“n 年前”计算:

from dateutil.relativedelta import relativedelta
import datetime

years_ago = datetime.datetime.now() - relativedelta(years=5)

然后只需更新 date 字段,如其他人所示。

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.

一个人的旅程 2024-11-11 10:30:39

使用 timedelta。像这样的事情应该可以解决问题:

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

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))
凌乱心跳 2024-11-11 10:30:39

Django 查询集上的 .update() 方法允许您更新所有值,而无需从数据库中检索对象。您可以使用 引用现有值F() 对象

不幸的是,Python 的 timedelta 不适用于年,因此您必须计算出以天表示的 100 年(即 36524.25):

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

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))
我最亲爱的 2024-11-11 10:30:39

虽然将一年中的天数设置为 365.25(来自 (365+365+365+366)/4)完美地抵消了天差误差,但有时会导致不需要的结果,因为您可能会导致除年份以外的属性发生不需要的更改,特别是当您添加/减去 1 或几年时。

如果您只想更改year,同时防止更改其他日期时间的属性,只需对year属性进行代数,如下所示:

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

希望它有帮助!

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!

空城缀染半城烟沙 2024-11-11 10:30:39

我知道这是一个老问题,但我无法找到一个好的问题来解决我的问题,我创建了这个:使用 plus(+) 或 minus(-) 来处理:

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

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
悲歌长辞 2024-11-11 10:30:39

最简单的方法是使用 dateutil.relativedelta 正如另一个答案中提到的。但是,如果您不想添加对 python-dateutil 的额外依赖项,则仅使用标准库模块即可轻松实现类似的逻辑:

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

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
同尘 2024-11-11 10:30:39

从今天减去年份并使用此格式。
x = 日期时间.日期时间(2020 - 100, 5, 17)

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

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文