您的位置:首页 > 编程语言 > Python开发

网上看到的计算python 月份增加的解决方法

2014-09-30 19:13 316 查看
感觉还不错,分享下。

def add_month(date):
"""add one month to date, maybe falling to last day of month

:param datetime.datetime date: the date

::
>>> add_month(datetime(2014,1,31))
datetime.datetime(2014, 2, 28, 0, 0)
>>> add_month(datetime(2014,12,30))
datetime.datetime(2015, 1, 30, 0, 0)
"""
# number of days this month
month_days = calendar.monthrange(date.year, date.month)[1]
candidate = date + timedelta(days=month_days)
# but maybe we are a month too far
if candidate.day != date.day:
# go to last day of next month,
# by getting one day before begin of candidate month
return candidate.replace(day=1) - timedelta(days=1)
else:
return candidate
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐