我需要增加一个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一样好的简单的解决方案吗?
不使用日历的解决方案:
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))
不使用日历的解决方案:
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))
def month_sub(year, month, sub_month):
result_month = 0
result_year = 0
if month > (sub_month % 12):
result_month = month - (sub_month % 12)
result_year = year - (sub_month / 12)
else:
result_month = 12 - (sub_month % 12) + month
result_year = year - (sub_month / 12 + 1)
return (result_year, result_month)
def month_add(year, month, add_month):
return month_sub(year, month, -add_month)
>>> month_add(2015, 7, 1)
(2015, 8)
>>> month_add(2015, 7, 20)
(2017, 3)
>>> month_add(2015, 7, 12)
(2016, 7)
>>> month_add(2015, 7, 24)
(2017, 7)
>>> month_add(2015, 7, -2)
(2015, 5)
>>> month_add(2015, 7, -12)
(2014, 7)
>>> month_add(2015, 7, -13)
(2014, 6)