我正在使用datetime Python模块。我希望从当前日期计算6个月的日期。有人能帮我一下吗?

我想从当前日期生成一个6个月后的日期的原因是为了生成一个回顾日期。如果用户在系统中输入数据,系统将有从输入数据之日起6个月的审查日期。


当前回答

使用Python标准库,即没有dateutil或其他,并解决“2月31日”问题:

import datetime
import calendar

def add_months(date, months):
    months_count = date.month + months

    # Calculate the year
    year = date.year + int(months_count / 12)

    # Calculate the month
    month = (months_count % 12)
    if month == 0:
        month = 12

    # Calculate the day
    day = date.day
    last_day_of_month = calendar.monthrange(year, month)[1]
    if day > last_day_of_month:
        day = last_day_of_month

    new_date = datetime.date(year, month, day)
    return new_date

测试:

>>>date = datetime.date(2018, 11, 30)

>>>print(date, add_months(date, 3))
(datetime.date(2018, 11, 30), datetime.date(2019, 2, 28))

>>>print(date, add_months(date, 14))
(datetime.date(2018, 12, 31), datetime.date(2020, 2, 29))

其他回答

我找不到这个问题的确切解决方案,所以我将发布我的解决方案,以防使用标准日历和datetime库可能有任何帮助。这适用于添加和减去月份,并考虑月末滚动和最后一个月比第一个月天数少的情况。如果你正在寻找更复杂的操作,我还有一个更通用的解决方案,它添加了定期间隔(天,月,年,季度,学期等),如:“1m”,“-9m”,“-1.5y”,“-3q”,“1s”等。

from datetime import datetime
from calendar import monthrange
def date_bump_months(start_date, months):
    """
    bumps months back and forth. 
    --> if initial date is end-of-month, i will move to corresponding month-end
    --> ir inital date.day is greater than end of month of final date, it casts it to momth-end
    """
    signbit = -1 if months < 0 else 1
    d_year, d_month = divmod(abs(months),12)    
    end_year = start_date.year + d_year*signbit 
    end_month = 0
    if signbit ==-1:            
        if d_month < start_date.month:
            end_month = start_date.month - d_month
        else:
            end_year -=1
            end_month = 12 - (d_month - start_date.month)
    else:
        end_month +=start_date.month
        if end_month  > 12:
            end_year +=1
            end_month -=12
    # check if we are running end-of-month dates
    eom_run = monthrange(start_date.year, start_date.month)[1]==start_date.day
    eom_month = monthrange((end_year), (end_month))[1]
    if eom_run:
        end_day = eom_month 
    else:
        end_day = min(start_date.day, eom_month )    
    return date(end_year, end_month, end_day)

下面是一个示例,它允许用户决定如何返回一个日期,其中一天大于一个月中的天数。

def add_months(date, months, endOfMonthBehaviour='RoundUp'):
    assert endOfMonthBehaviour in ['RoundDown', 'RoundIn', 'RoundOut', 'RoundUp'], \
        'Unknown end of month behaviour'
    year = date.year + (date.month + months - 1) / 12
    month = (date.month + months - 1) % 12 + 1
    day = date.day
    last = monthrange(year, month)[1]
    if day > last:
        if endOfMonthBehaviour == 'RoundDown' or \
            endOfMonthBehaviour == 'RoundOut' and months < 0 or \
            endOfMonthBehaviour == 'RoundIn' and months > 0:
            day = last
        elif endOfMonthBehaviour == 'RoundUp' or \
            endOfMonthBehaviour == 'RoundOut' and months > 0 or \
            endOfMonthBehaviour == 'RoundIn' and months < 0:
            # we don't need to worry about incrementing the year
            # because there will never be a day in December > 31
            month += 1
            day = 1
    return datetime.date(year, month, day)


>>> from calendar import monthrange
>>> import datetime
>>> add_months(datetime.datetime(2016, 1, 31), 1)
datetime.date(2016, 3, 1)
>>> add_months(datetime.datetime(2016, 1, 31), -2)
datetime.date(2015, 12, 1)
>>> add_months(datetime.datetime(2016, 1, 31), -2, 'RoundDown')
datetime.date(2015, 11, 30)

Python可以使用datautil包,请参阅下面的示例

它不仅限于此,你还可以同时通过日、月和年的组合。

import datetime
from dateutil.relativedelta import relativedelta

# subtract months
proc_dt = datetime.date(2021,8,31)
proc_dt_minus_3_months = proc_dt + relativedelta(months=-3)
print(proc_dt_minus_3_months)

# add months
proc_dt = datetime.date(2021,8,31)
proc_dt_plus_3_months = proc_dt + relativedelta(months=+3)
print(proc_dt_plus_3_months)

# subtract days:
proc_dt = datetime.date(2021,8,31)
proc_dt_minus_3_days = proc_dt + relativedelta(days=-3)
print(proc_dt_minus_3_days)

# add days days:
proc_dt = datetime.date(2021,8,31)
proc_dt_plus_3_days = proc_dt + relativedelta(days=+3)
print(proc_dt_plus_3_days)

# subtract years:
proc_dt = datetime.date(2021,8,31)
proc_dt_minus_3_years = proc_dt + relativedelta(years=-3)
print(proc_dt_minus_3_years)

# add years:
proc_dt = datetime.date(2021,8,31)
proc_dt_plus_3_years = proc_dt + relativedelta(years=+3)
print(proc_dt_plus_3_years)

结果:

2021-05-31

2021-11-30

2021-08-28

2021-09-03

2018-08-31

2024-08-31

Python的datetime没有直接的方法来做到这一点。

在python-dateutil中查看relativedelta类型。它允许您指定以月为单位的时间增量。

使用Python标准库,即没有dateutil或其他,并解决“2月31日”问题:

import datetime
import calendar

def add_months(date, months):
    months_count = date.month + months

    # Calculate the year
    year = date.year + int(months_count / 12)

    # Calculate the month
    month = (months_count % 12)
    if month == 0:
        month = 12

    # Calculate the day
    day = date.day
    last_day_of_month = calendar.monthrange(year, month)[1]
    if day > last_day_of_month:
        day = last_day_of_month

    new_date = datetime.date(year, month, day)
    return new_date

测试:

>>>date = datetime.date(2018, 11, 30)

>>>print(date, add_months(date, 3))
(datetime.date(2018, 11, 30), datetime.date(2019, 2, 28))

>>>print(date, add_months(date, 14))
(datetime.date(2018, 12, 31), datetime.date(2020, 2, 29))