如何使用 datetime Python 模块计算从当前日期算起六个月的日期? [英] How do I calculate the date six months from the current date using the datetime Python module?

查看:36
本文介绍了如何使用 datetime Python 模块计算从当前日期算起六个月的日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用日期时间 Python 模块.我希望计算从当前日期算起 6 个月的日期.有人可以帮我做这件事吗?

I am using the datetime Python module. I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?

我想生成一个距当前日期 6 个月的日期的原因是为了生成一个审查日期.如果用户将数据输入系统,则自输入数据之日起,审查日期为 6 个月.

The reason I want to generate a date 6 months from the current date is to produce a review date. If the user enters data into the system it will have a review date of 6 months from the date they entered the data.

推荐答案

我发现这个解决方案很好.(这使用 python-dateutil 扩展)

I found this solution to be good. (This uses the python-dateutil extension)

from datetime import date
from dateutil.relativedelta import relativedelta

six_months = date.today() + relativedelta(months=+6)

这种方法的优点是可以处理 28、30、31 天等问题.这在处理业务规则和场景(例如发票生成等)时非常有用

The advantage of this approach is that it takes care of issues with 28, 30, 31 days etc. This becomes very useful in handling business rules and scenarios (say invoice generation etc.)

$ date(2010,12,31)+relativedelta(months=+1)
  datetime.date(2011, 1, 31)

$ date(2010,12,31)+relativedelta(months=+2)
  datetime.date(2011, 2, 28)

这篇关于如何使用 datetime Python 模块计算从当前日期算起六个月的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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