python datetime 加一个月,如何在python中自定义月份增加datetime,而不使用库

I need to increment the month of a datetime value

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

when the month is 12, it becomes 13 and raises error "month must be in 1..12". (I expected the year would increment)

I wanted to use timedelta, but it doesn't take month argument.

There is relativedelta python package, but i don't want to install it just only for this.

Also there is a solution using strtotime.

time = strtotime(str(mydate));

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

I don't want to convert from datetime to str then to time, and then to datetime; therefore, it's still a library too

Does anyone have any good and simple solution just like using timedelta?

解决方案

Edit - based on your comment of dates being needed to be rounded down if there are fewer days in the next month, here is a solution:

>>> import datetime

>>> import calendar

>>>

>>> def add_months(sourcedate,months):

... month = sourcedate.month - 1 + months

... year = int(sourcedate.year + month / 12 )

... month = month % 12 + 1

... day = min(sourcedate.day,calendar.monthrange(year,month)[1])

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

...

>>> somedate = datetime.date.today()

>>> somedate

datetime.date(2010, 11, 9)

>>> add_months(somedate,1)

datetime.date(2010, 12, 9)

>>> add_months(somedate,23)

datetime.date(2012, 10, 9)

>>> otherdate = datetime.date(2010,10,31)

>>> add_months(otherdate,1)

datetime.date(2010, 11, 30)

Also, if you're not worried about hours, minutes and seconds you could use date rather than datetime. If you are worried about hours, minutes and seconds you need to modify my code to use datetime and copy hours, minutes and seconds from the source to the result.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值