如果我有两个约会(例如。'8/18/2008'和'9/26/2008'),怎样才能得到这两个日期之间的天数?


当前回答

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

当然,这假设您已经验证了日期的格式为r'\d+/\d+/\d+'。

其他回答

您需要datetime模块。

>>> from datetime import datetime 
>>> datetime(2008,08,18) - datetime(2008,09,26) 
datetime.timedelta(4) 

另一个例子:

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

正如这里所指出的

如果您有两个date对象,您可以将它们相减,这将计算一个timedelta对象。

from datetime import date

d0 = date(2008, 8, 18)
d1 = date(2008, 9, 26)
delta = d1 - d0
print(delta.days)

文档的相关部分: https://docs.python.org/library/datetime.html。

请看另一个例子。

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 datetime

Now = datetime.now()
StartDate = datetime.strptime(str(Now.year) +'-01-01', '%Y-%m-%d')
NumberOfDays = (Now - StartDate)

print(NumberOfDays.days)                     # Starts at 0
print(datetime.now().timetuple().tm_yday)    # Starts at 1
print(Now.strftime('%j'))                    # Starts at 1

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

当然,这假设您已经验证了日期的格式为r'\d+/\d+/\d+'。