如果我有两个约会(例如。'8/18/2008'和'9/26/2008'),怎样才能得到这两个日期之间的天数?
当前回答
在python中不使用datetime对象。
# A date has day 'd', month 'm' and year 'y'
class Date:
def __init__(self, d, m, y):
self.d = d
self.m = m
self.y = y
# To store number of days in all months from
# January to Dec.
monthDays = [31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31 ]
# This function counts number of leap years
# before the given date
def countLeapYears(d):
years = d.y
# Check if the current year needs to be considered
# for the count of leap years or not
if (d.m <= 2) :
years-= 1
# An year is a leap year if it is a multiple of 4,
# multiple of 400 and not a multiple of 100.
return int(years / 4 - years / 100 + years / 400 )
# This function returns number of days between two
# given dates
def getDifference(dt1, dt2) :
# COUNT TOTAL NUMBER OF DAYS BEFORE FIRST DATE 'dt1'
# initialize count using years and day
n1 = dt1.y * 365 + dt1.d
# Add days for months in given date
for i in range(0, dt1.m - 1) :
n1 += monthDays[i]
# Since every leap year is of 366 days,
# Add a day for every leap year
n1 += countLeapYears(dt1)
# SIMILARLY, COUNT TOTAL NUMBER OF DAYS BEFORE 'dt2'
n2 = dt2.y * 365 + dt2.d
for i in range(0, dt2.m - 1) :
n2 += monthDays[i]
n2 += countLeapYears(dt2)
# return difference between two counts
return (n2 - n1)
# Driver program
dt1 = Date(31, 12, 2018 )
dt2 = Date(1, 1, 2019 )
print(getDifference(dt1, dt2), "days")
其他回答
使用datetime函数:
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
不使用Lib只是纯代码:
#Calculate the Days between Two Date
daysOfMonths = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def isLeapYear(year):
# Pseudo code for this algorithm is found at
# http://en.wikipedia.org/wiki/Leap_year#Algorithm
## if (year is not divisible by 4) then (it is a common Year)
#else if (year is not divisable by 100) then (ut us a leap year)
#else if (year is not disible by 400) then (it is a common year)
#else(it is aleap year)
return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0
def Count_Days(year1, month1, day1):
if month1 ==2:
if isLeapYear(year1):
if day1 < daysOfMonths[month1-1]+1:
return year1, month1, day1+1
else:
if month1 ==12:
return year1+1,1,1
else:
return year1, month1 +1 , 1
else:
if day1 < daysOfMonths[month1-1]:
return year1, month1, day1+1
else:
if month1 ==12:
return year1+1,1,1
else:
return year1, month1 +1 , 1
else:
if day1 < daysOfMonths[month1-1]:
return year1, month1, day1+1
else:
if month1 ==12:
return year1+1,1,1
else:
return year1, month1 +1 , 1
def daysBetweenDates(y1, m1, d1, y2, m2, d2,end_day):
if y1 > y2:
m1,m2 = m2,m1
y1,y2 = y2,y1
d1,d2 = d2,d1
days=0
while(not(m1==m2 and y1==y2 and d1==d2)):
y1,m1,d1 = Count_Days(y1,m1,d1)
days+=1
if end_day:
days+=1
return days
# Test Case
def test():
test_cases = [((2012,1,1,2012,2,28,False), 58),
((2012,1,1,2012,3,1,False), 60),
((2011,6,30,2012,6,30,False), 366),
((2011,1,1,2012,8,8,False), 585 ),
((1994,5,15,2019,8,31,False), 9239),
((1999,3,24,2018,2,4,False), 6892),
((1999,6,24,2018,8,4,False),6981),
((1995,5,24,2018,12,15,False),8606),
((1994,8,24,2019,12,15,True),9245),
((2019,12,15,1994,8,24,True),9245),
((2019,5,15,1994,10,24,True),8970),
((1994,11,24,2019,8,15,True),9031)]
for (args, answer) in test_cases:
result = daysBetweenDates(*args)
if result != answer:
print "Test with data:", args, "failed"
else:
print "Test case passed!"
test()
在python中不使用datetime对象。
# A date has day 'd', month 'm' and year 'y'
class Date:
def __init__(self, d, m, y):
self.d = d
self.m = m
self.y = y
# To store number of days in all months from
# January to Dec.
monthDays = [31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31 ]
# This function counts number of leap years
# before the given date
def countLeapYears(d):
years = d.y
# Check if the current year needs to be considered
# for the count of leap years or not
if (d.m <= 2) :
years-= 1
# An year is a leap year if it is a multiple of 4,
# multiple of 400 and not a multiple of 100.
return int(years / 4 - years / 100 + years / 400 )
# This function returns number of days between two
# given dates
def getDifference(dt1, dt2) :
# COUNT TOTAL NUMBER OF DAYS BEFORE FIRST DATE 'dt1'
# initialize count using years and day
n1 = dt1.y * 365 + dt1.d
# Add days for months in given date
for i in range(0, dt1.m - 1) :
n1 += monthDays[i]
# Since every leap year is of 366 days,
# Add a day for every leap year
n1 += countLeapYears(dt1)
# SIMILARLY, COUNT TOTAL NUMBER OF DAYS BEFORE 'dt2'
n2 = dt2.y * 365 + dt2.d
for i in range(0, dt2.m - 1) :
n2 += monthDays[i]
n2 += countLeapYears(dt2)
# return difference between two counts
return (n2 - n1)
# Driver program
dt1 = Date(31, 12, 2018 )
dt2 = Date(1, 1, 2019 )
print(getDifference(dt1, dt2), "days")
它也可以很容易地用箭头完成:
import arrow
a = arrow.get('2017-05-09')
b = arrow.get('2017-05-11')
delta = (b-a)
print delta.days
参考:http://arrow.readthedocs.io/en/latest/
您需要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
正如这里所指出的
推荐文章
- python中的assertEquals和assertEqual
- 如何保持Python打印不添加换行符或空格?
- 为什么Python的无穷散列中有π的数字?
- Python 3.7数据类中的类继承
- 如何在PyTorch中初始化权重?
- 计数唯一的值在一列熊猫数据框架像在Qlik?
- 使用Pandas将列转换为行
- 从matplotlib中的颜色映射中获取单个颜色
- 将Pandas或Numpy Nan替换为None以用于MysqlDB
- 使用pandas对同一列进行多个聚合
- 使用Python解析HTML
- django MultiValueDictKeyError错误,我如何处理它
- 如何在for循环期间修改列表条目?
- 我如何在Django中创建一个鼻涕虫?
- 我如何预填充一个jQuery Datepicker文本框与今天的日期?