我需要增加一个datetime值的月份

next_month = datetime.datetime(mydate.year, mydate.month+1, 1)

当月份为12时,它变成13,并引发错误“month必须在1..12”。(我预计时间会增加)

我想使用timedelta,但它不带month参数。 有一个relativedelta python包,但我不想只为此安装它。 还有一个使用strtotime的解决方案。

time = strtotime(str(mydate));
next_month = date("Y-m-d", strtotime("+1 month", time));

我不想从datetime转换为str再转换为time,再转换为datetime;因此,它仍然是一个图书馆

有人有像使用timedelta一样好的简单的解决方案吗?


当前回答

使用monthdelta包,它就像timedelta一样工作,但适用于日历月,而不是天/小时/等等。

这里有一个例子:

from monthdelta import MonthDelta

def prev_month(date):
    """Back one month and preserve day if possible"""
    return date + MonthDelta(-1)

将其与DIY方法进行比较:

def prev_month(date):
    """Back one month and preserve day if possible"""
   day_of_month = date.day
   if day_of_month != 1:
           date = date.replace(day=1)
   date -= datetime.timedelta(days=1)
   while True:
           try:
                   date = date.replace(day=day_of_month)
                   return date
           except ValueError:
                   day_of_month -= 1               

其他回答

这是我想到的

from calendar  import monthrange

def same_day_months_after(start_date, months=1):
    target_year = start_date.year + ((start_date.month + months) / 12)
    target_month = (start_date.month + months) % 12
    num_days_target_month = monthrange(target_year, target_month)[1]
    return start_date.replace(year=target_year, month=target_month, 
        day=min(start_date.day, num_days_target_month))

由于没有人提出任何解决方案,这里是我目前为止解决的方法

year, month= divmod(mydate.month+1, 12)
if month == 0: 
      month = 12
      year = year -1
next_month = datetime.datetime(mydate.year + year, month, 1)

不使用日历的解决方案:

def add_month_year(date, years=0, months=0):
    year, month = date.year + years, date.month + months + 1
    dyear, month = divmod(month - 1, 12)
    rdate = datetime.date(year + dyear, month + 1, 1) - datetime.timedelta(1)
    return rdate.replace(day = min(rdate.day, date.day))

最简单的解决方法是在月底去(我们都知道每个月至少有28天),并增加足够的时间来研究下一个飞蛾:

>>> from datetime import datetime, timedelta
>>> today = datetime.today()
>>> today
datetime.datetime(2014, 4, 30, 11, 47, 27, 811253)
>>> (today.replace(day=28) + timedelta(days=10)).replace(day=today.day)
datetime.datetime(2014, 5, 30, 11, 47, 27, 811253)

也适用于不同的年份:

>>> dec31
datetime.datetime(2015, 12, 31, 11, 47, 27, 811253)
>>> today = dec31
>>> (today.replace(day=28) + timedelta(days=10)).replace(day=today.day)
datetime.datetime(2016, 1, 31, 11, 47, 27, 811253)

请记住,不能保证下个月将有相同的日子,例如从1月31日移动到2月31日,它将失败:

>>> today
datetime.datetime(2016, 1, 31, 11, 47, 27, 811253)
>>> (today.replace(day=28) + timedelta(days=10)).replace(day=today.day)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: day is out of range for month

因此,如果您需要移动到下个月的第一天,这是一个有效的解决方案,因为您总是知道下个月是第1天(.replace(day=1))。否则,要移动到最后可用的一天,你可能想使用:

>>> today
datetime.datetime(2016, 1, 31, 11, 47, 27, 811253)
>>> next_month = (today.replace(day=28) + timedelta(days=10))
>>> import calendar
>>> next_month.replace(day=min(today.day, 
                               calendar.monthrange(next_month.year, next_month.month)[1]))
datetime.datetime(2016, 2, 29, 11, 47, 27, 811253)

这个怎么样?(不需要任何额外的库)

from datetime import date, timedelta
from calendar import monthrange

today = date.today()
month_later = date(today.year, today.month, monthrange(today.year, today.month)[1]) + timedelta(1)