如何在python中自定义月份增加datetime,而不使用库 [英] How to increment datetime by custom months in python without using library

查看:604
本文介绍了如何在python中自定义月份增加datetime,而不使用库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要增加日期时间值的月份

I need to increment the month of a datetime value

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

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

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

我想使用timedelta,但不需要月参数。
relativedelta python包,但我不想仅仅为了安装它。
还有一个使用 strtotime 的解决方案。

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));

我不想将datetime转换为str,然后转换为datetime;因此,它仍然是图书馆

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

有没有人有任何好的和简单的解决方案,就像使用timedelta?

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)

另外如果您不用担心小时,分钟和秒数,您可以使用 date 而不是 datetime 。如果您担心几小时,几分钟和几秒钟,您需要修改我的代码以使用 datetime ,并从源头复制到结果的小时,分​​和秒。

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.

这篇关于如何在python中自定义月份增加datetime,而不使用库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆