如何在Django数据库中的datetime字段中减去或添加100年? [英] How can I subtract or add 100 years to a datetime field in the database in Django?

查看:1201
本文介绍了如何在Django数据库中的datetime字段中减去或添加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.

推荐答案

使用dateutil.relativedelta包的relativedelta函数,这将使您更准确的n年前计算:

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.

这篇关于如何在Django数据库中的datetime字段中减去或添加100年?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆