从日期时间减去 1 年

发布于 08-30 16:45 字数 306 浏览 16 评论 0原文

我看过很多关于如何从一个日期时间中减去另一个日期时间以及如何在日期时间上添加年份的信息。但以下内容让我头疼......

当用户插入一条记录时,一个名为 subdate 且值为 datetime.now 的隐藏字段将添加到数据库中。

然后,我需要一个“旧记录”页面,列出所有超过 1 年的条目,并希望使用类似于以下内容的内容(但使用减法):

(DateTime.Now.AddYears(1))

但没有 SubtractYears 可用?为什么?

请问你能告诉我如何达到同样的结果吗?

I have seen a lot of info on how to subtract one datetime from the other and how to add years on to a datetime. but the following is giving me a headache....

When a user inserts a record a hidden field called subdate with a value of datetime.now is added to the db.

I then need to have an 'old records' page that lists all the entries that are over 1 year old and was hoping to use something (but using subtract method) similar to;

(DateTime.Now.AddYears(1))

but there is no SubtractYears available? Why?

Please can you let me know how I achieve the same result?

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

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

发布评论

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

评论(2

云醉月微眠2024-09-06 16:45:48
DateTime.Now.AddYears(-1)

来自文档

很多年了。 value 参数可以是负值也可以是正值。

DateTime.Now.AddYears(-1)

From the documentation:

A number of years. The value parameter can be negative or positive.

世界如花海般美丽2024-09-06 16:45:48
now = datetime.now()
last_year = (now.year - 1)
datestr = (datetime.strptime(str(now.year - 1), "%Y")).strftime("%y")
print(f"Last Year: {datestr}")

输出将为:

去年:20

如果您更喜欢四位数年份,则将 %y 更改为 %Y

now = datetime.now()
last_year = (now.year - 1)
datestr = (datetime.strptime(str(now.year - 1), "%Y")).strftime("%y")
print(f"Last Year: {datestr}")

The output will be:

Last Year: 20

If you prefer to have four digit year then change %y to %Y

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