python datetime 加一个月_python时间模块,如何让时间一次改变一个月?

展开全部

Python语言: Python中按月增加datetime

1653#coding=utf-8

#from:

import datetime

# input datetime1, and an month offset

# return the result datetime

def datetime_offset_by_month(datetime1, n = 1):

# create a shortcut object for one day

one_day = datetime.timedelta(days = 1)

# first use div and mod to determine year cycle

q,r = divmod(datetime1.month + n, 12)

# create a datetime2

# to be the last day of the target month

datetime2 = datetime.datetime(

datetime1.year + q, r + 1, 1) - one_day

# if input date is the last day of this month

# then the output date should also be the last

# day of the target month, although the day

# may be different.

# for example:

# datetime1 = 8.31

# datetime2 = 9.30

if datetime1.month != (datetime1 + one_day).month:

return datetime2

# if datetime1 day is bigger than last day of

# target month, then, use datetime2

# for example:

# datetime1 = 10.31

# datetime2 = 11.30

if datetime1.day >= datetime2.day:

return datetime2

# then, here, we just replace datetime2's day

# with the same of datetime1, that's ok.

return datetime2.replace(day = datetime1.day)

#------------------------------------------

# test

d1 = datetime.datetime(2008, 8, 17)

d2 = datetime_offset_by_month(d1, 13)

print '2008-8-17 + 13 month'

print d2

print

d1 = datetime.datetime(2008, 8, 31)

d2 = datetime_offset_by_month(d1, 13)

print '2008-8-31 + 13 month'

print d2

print

d1 = datetime.datetime(2007, 1, 30)

d2 = datetime_offset_by_month(d1, 13)

print '2007-1-30 + 13 month'

print d2

print

result = """

2008-8-17 + 13 month

2009-09-17 00:00:00

2008-8-31 + 13 month

2009-09-30 00:00:00

2007-1-30 + 13 month

2008-02-29 00:00:00

"""

2Q==

已赞过

已踩过<

你对这个回答的评价是?

评论

收起

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值