如何使用Python计算两个date之间的天数?
如果我有两个date(例如'8/18/2008'
和'9/26/2008'
),获得两个date之间的天数的最佳方法是什么?
如果你有两个date对象,你可以减去它们。
from datetime import date d0 = date(2008, 8, 18) d1 = date(2008, 9, 26) delta = d0 - d1 print delta.days
文档的相关部分: https : //docs.python.org/library/datetime.html
使用date时间的力量:
from datetime import datetime date_format = "%m/%d/%Y" a = datetime.strptime('8/18/2008', date_format) b = datetime.strptime('9/26/2008', date_format) delta = b - a print delta.days # that's it
直到圣诞节的日子
>>> import datetime >>> today = datetime.date.today() >>> someday = datetime.date(2008, 12, 25) >>> diff = someday - today >>> diff.days 86
这里更多的算术。
你想要的date时间模块。
>>> from datetime import datetime >>> datetime(2008,08,18) - datetime(2008,09,26) datetime.timedelta(4)
或者其他例子:
Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53) [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import datetime >>> today = datetime.date.today() >>> print today 2008-09-01 >>> last_year = datetime.date(2007, 9, 1) >>> print today - last_year 366 days, 0:00:00
正如这里指出的那样
from datetime import datetime start_date = datetime.strptime('8/18/2008', "%m/%d/%Y") end_date = datetime.strptime('9/26/2008', "%m/%d/%Y") print abs((end_date-start_date).days)
from datetime import date def d(s): [month, day, year] = map(int, s.split('/')) return date(year, month, day) def days(start, end): return (d(end) - d(start)).days print days('8/18/2008', '9/26/2008')
这当然假设你已经validation了你的date是r'\d+/\d+/\d+'
的格式。
这也可以很容易地用arrow
完成:
import arrow a = arrow.get('2017-05-09') b = arrow.get('2017-05-11') delta = (ba) print delta.days
供参考: http : //arrow.readthedocs.io/en/latest/