如何使用datetime Python模块计算从当前日期起六个月的日期?

我正在使用datetime Python模块。 我想计算从当前日期起6个月的日期。 有人能够给我一点帮助吗? app

我要从当前日期起6个月生成日期的缘由是要产生一个审阅日期 。 若是用户将数据输入到系统中,则其输入日期为6个月。 函数


#1楼

PyQt4的QDate类具备addmonths函数。 ui

>>>from PyQt4.QtCore import QDate  
>>>dt = QDate(2009,12,31)  
>>>required = dt.addMonths(6) 

>>>required
PyQt4.QtCore.QDate(2010, 6, 30)

>>>required.toPyDate()
datetime.date(2010, 6, 30)

#2楼

另外一个解决方案-但愿有人会喜欢它: spa

def add_months(d, months):
    return d.replace(year=d.year+months//12).replace(month=(d.month+months)%12)

该解决方案在全部状况下都没法正常工做29,30,31天,所以须要更强大的解决方案(如今再也不那么好了:)): code

def add_months(d, months):
    for i in range(4):
        day = d.day - i
        try:
            return d.replace(day=day).replace(year=d.year+int(months)//12).replace(month=(d.month+int(months))%12)
        except:
            pass
    raise Exception("should not happen")

#3楼

在1new_month = 121的状况下修改了Johannes Wei的答案。这对我来讲很是有效。 月份能够是正数或负数。 io

def addMonth(d,months=1):
    year, month, day = d.timetuple()[:3]
    new_month = month + months
    return datetime.date(year + ((new_month-1) / 12), (new_month-1) % 12 +1, day)

#4楼

这就是我想出的。 它能够移动正确的月数和年数,但会忽略天数(这是我当时所须要的)。 import

import datetime

month_dt = 4
today = datetime.date.today()
y,m = today.year, today.month
m += month_dt-1
year_dt = m//12
new_month = m%12
new_date = datetime.date(y+year_dt, new_month+1, 1)

#5楼

我使用此功能更改年份和月份,但保留日期: require

def replace_month_year(date1, year2, month2):
    try:
        date2 = date1.replace(month = month2, year = year2)
    except:
        date2 = datetime.date(year2, month2 + 1, 1) - datetime.timedelta(days=1)
    return date2

您应该写: date

new_year = my_date.year + (my_date.month + 6) / 12
new_month = (my_date.month + 6) % 12
new_date = replace_month_year(my_date, new_year, new_month)
相关文章
相关标签/搜索