6 month before date in python
本问题已经有最佳答案,请猛点这里访问。
我想在python中计算日期之前的6个月。那么在日期(例如8月31日)是否有任何问题发生。我们可以使用timedelta()函数解决这个问题。我们可以传递像date=now-timedelta(days=days)这样的月份而不是参数days。
示例-
1 2 3 4 5 6 7 8 9 | >>> from dateutil import relativedelta >>> from datetime import datetime >>> n = datetime.now() >>> n - relativedelta.relativedelta(months=6) datetime.datetime(2015, 1, 30, 10, 5, 32, 491815) >>> n - relativedelta.relativedelta(months=8) datetime.datetime(2014, 11, 30, 10, 5, 32, 491815) |
号
以下函数在月加法和月减法中都可以正常工作。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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) #Example: Get today dateToday = datetime.date.today() #Substract 6 month from Today print add_months(dateToday ,-6) |
如果您只对6个月前的月份感兴趣,请尝试以下操作:
1 2 3 4 5 | import datetime month = datetime.datetime.now().month - 6 if month < 1: month = 12 + month # At this point month is 0 or a negative number so we add |