2015年12月3日 星期四

[ Python 常見問題 ] How to increment datetime by custom months in python without using library?

Source From Here
Question
I need to increment the month of a datetime value. 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 usingstrtotime. Below is the example usage:
>>> import timelib
>>> today = timelib.strtodatetime('today')
>>> today
datetime.datetime(2015, 12, 3, 0, 0)
>>> timelib.strtodatetime('next friday')
datetime.datetime(2015, 12, 4, 0, 0)
>>> from datetime import date
>>> next_month_obj = date.fromtimestamp(next_month)
>>> next_month_obj
datetime.date(2016, 1, 3)
>>> from timelib import strtotime
>>> strtotime('+1 year', strtotime('today'))
1480723200
>>> date.fromtimestamp(strtotime('+1 year', strtotime('today')))
datetime.date(2016, 12, 2)

Does anyone have any good and simple solution besides above approaches?

How-To
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:
- demo.py
  1. #!/usr/bin/env python  
  2. import datetime  
  3. import calendar  
  4.   
  5. def add_months(sourcedate,months):  
  6.         month = sourcedate.month - 1 + months  
  7.         year = int(sourcedate.year + month / 12 )  
  8.         month = month % 12 + 1  
  9.         day = min(sourcedate.day,calendar.monthrange(year,month)[1])  
  10.         return datetime.date(year,month,day)  
  11.   
  12. somedate = datetime.date.today()  
  13. print('Today = %s' % somedate)  
  14. print('Add one month from today = %s' % add_months(somedate,1))  
  15. print('Add 23 Months from today = %s' % add_months(somedate,23))  
  16. otherdate = datetime.date(2010,10,31)  
  17. print('Add one month from %s = %s' % (otherdate, add_months(otherdate,1)))  
Execution result:
# ./demo.py
Today = 2015-12-03
Add one month from today = 2016-01-03
Add 23 Months from today = 2017-11-03
Add one month from 2010-10-31 = 2010-11-30


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...