如何在不使用库的情况下在python中按自定义月份增加日期时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4130922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to increment datetime by custom months in python without using library
提问by jargalan
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)
当月份为 12 时,它变为 13 并引发错误“月份必须在 1..12”。(我预计年份会增加)
I wanted to use timedelta, but it doesn't take month argument. There is relativedeltapython package, but i don't want to install it just only for this. Also there is a solution using strtotime.
我想使用 timedelta,但不需要月份参数。有relativedeltapython 包,但我不想只为此安装它。还有一个使用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
我不想从日期时间转换为 str,然后转换为时间,然后转换为日期时间;因此,它仍然是一个图书馆
Does anyone have any good and simplesolution just like using timedelta?
有没有人有任何好的和简单的解决方案,就像使用 timedelta 一样?
采纳答案by Dave Webb
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 = sourcedate.year + month // 12
month = month % 12 + 1
day = min(sourcedate.day, calendar.monthrange(year,month)[1])
return datetime.date(year, month, day)
In use:
正在使用:
>>> 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 daterather than datetime. If you are worried about hours, minutes and seconds you need to modify my code to use datetimeand copy hours, minutes and seconds from the source to the result.
此外,如果您不担心小时、分钟和秒,您可以使用date而不是datetime. 如果您担心小时、分钟和秒,您需要修改我的代码以使用datetime并将小时、分钟和秒从源复制到结果。
回答by dcolish
Well with some tweaks and use of timedeltahere we go:
通过一些调整和timedelta 的使用,我们开始了:
from datetime import datetime, timedelta
def inc_date(origin_date):
day = origin_date.day
month = origin_date.month
year = origin_date.year
if origin_date.month == 12:
delta = datetime(year + 1, 1, day) - origin_date
else:
delta = datetime(year, month + 1, day) - origin_date
return origin_date + delta
final_date = inc_date(datetime.today())
print final_date.date()
回答by jargalan
since no one suggested any solution, here is how i solved so far
由于没有人提出任何解决方案,这是我到目前为止的解决方法
year, month= divmod(mydate.month+1, 12)
if month == 0:
month = 12
year = year -1
next_month = datetime.datetime(mydate.year + year, month, 1)
回答by uzi
Perhaps add the number of days in the current month using calendar.monthrange()?
也许使用 calendar.monthrange() 添加当月的天数?
import calendar, datetime
def increment_month(when):
days = calendar.monthrange(when.year, when.month)[1]
return when + datetime.timedelta(days=days)
now = datetime.datetime.now()
print 'It is now %s' % now
print 'In a month, it will be %s' % increment_month(now)
回答by Matthew Schinckel
Similar in ideal to Dave Webb's solution, but without all of that tricky modulo arithmetic:
与 Dave Webb 的解决方案理想类似,但没有所有那些棘手的模运算:
import datetime, calendar
def increment_month(date):
# Go to first of this month, and add 32 days to get to the next month
next_month = date.replace(day=1) + datetime.timedelta(32)
# Get the day of month that corresponds
day = min(date.day, calendar.monthrange(next_month.year, next_month.month)[1])
return next_month.replace(day=day)
回答by karl
example using the time object:
使用时间对象的示例:
start_time = time.gmtime(time.time()) # start now
#increment one month
start_time = time.gmtime(time.mktime([start_time.tm_year, start_time.tm_mon+1, start_time.tm_mday, start_time.tm_hour, start_time.tm_min, start_time.tm_sec, 0, 0, 0]))
回答by Oliver Wienand
A solution without the use of calendar:
不使用日历的解决方案:
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))
回答by Eric Clack
Use the monthdeltapackage, it works just like timedelta but for calendar months rather than days/hours/etc.
使用monthdelta包,它的工作方式与 timedelta 一样,但适用于日历月而不是天/小时/等。
Here's an example:
下面是一个例子:
from monthdelta import MonthDelta
def prev_month(date):
"""Back one month and preserve day if possible"""
return date + MonthDelta(-1)
Compare that to the DIY approach:
将其与 DIY 方法进行比较:
def prev_month(date):
"""Back one month and preserve day if possible"""
day_of_month = date.day
if day_of_month != 1:
date = date.replace(day=1)
date -= datetime.timedelta(days=1)
while True:
try:
date = date.replace(day=day_of_month)
return date
except ValueError:
day_of_month -= 1
回答by pilou
My very simple solution, which doesn't require any additional modules:
我非常简单的解决方案,不需要任何额外的模块:
def addmonth(date):
if date.day < 20:
date2 = date+timedelta(32)
else :
date2 = date+timedelta(25)
date2.replace(date2.year, date2.month, day)
return date2
回答by Atul Arvind
This is short and sweet method to add a month to a date using dateutil's relativedelta.
from datetime import datetime
from dateutil.relativedelta import relativedelta
date_after_month = datetime.today()+ relativedelta(months=1)
print 'Today: ',datetime.today().strftime('%d/%m/%Y')
print 'After Month:', date_after_month.strftime('%d/%m/%Y')
Output:
输出:
Today: 01/03/2013
After Month: 01/04/2013
今天:01/03/2013
一个月后:01/04/2013
A word of warning: relativedelta(months=1)and relativedelta(month=1)have different meanings. Passing month=1will replacethe month in original date to January whereas passing months=1will add one month to original date.
一句话警告:relativedelta(months=1)和relativedelta(month=1)有不同的含义。通过month=1将原始日期中的月份替换为一月,而通过months=1将在原始日期上增加一个月。
Note: this will requires python-dateutil. To install it you need to run in Linux terminal.
注意:这将需要python-dateutil. 要安装它,您需要在 Linux 终端中运行。
sudo apt-get update && sudo apt-get install python-dateutil
Explanation : Add month value in python

