如何在 Django 数据库中的日期时间字段中减去或加上 100 年?
如何在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
我将使用
dateutil.relativedelta
包的relativedelta
函数,这将为您提供更准确的“n 年前”计算:然后只需更新
date
字段,如其他人所示。I would use the
relativedelta
function of thedateutil.relativedelta
package, which will give you are more accurate 'n-years ago' calculation:Then simply update the
date
field as others have shown here.使用 timedelta。像这样的事情应该可以解决问题:
Use timedelta. Something like this should do the trick:
Django 查询集上的
.update()
方法允许您更新所有值,而无需从数据库中检索对象。您可以使用 引用现有值F()
对象。不幸的是,Python 的 timedelta 不适用于年,因此您必须计算出以天表示的 100 年(即 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 anF()
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):
虽然将一年中的天数设置为
365.25
(来自(365+365+365+366)/4
)完美地抵消了天差误差,但有时会导致不需要的结果,因为您可能会导致除年份
以外的属性发生不需要的更改,特别是当您添加/减去 1 或几年时。如果您只想更改
year
,同时防止更改其他日期时间的属性,只需对year
属性进行代数,如下所示:希望它有帮助!
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 thanyear
, 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 theyear
attribute like the following:Hope it helps!
我知道这是一个老问题,但我无法找到一个好的问题来解决我的问题,我创建了这个:使用 plus(+) 或 minus(-) 来处理:
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:
最简单的方法是使用
dateutil.relativedelta
正如另一个答案中提到的。但是,如果您不想添加对 python-dateutil 的额外依赖项,则仅使用标准库模块即可轻松实现类似的逻辑: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 onpython-dateutil
, it's pretty easy to implement a similar logic using only standard library modules:从今天减去年份并使用此格式。
x = 日期时间.日期时间(2020 - 100, 5, 17)
Subtract year from today and use this format.
x = datetime.datetime(2020 - 100, 5, 17)