666

如果我有两个日期(例如'8/18/2008''9/26/2008'),获取这两个日期之间天数的最佳方法是什么?

4

14 回答 14

1031

如果您有两个日期对象,您可以将它们相减,从而计算出一个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 。

有关另一个示例,请参见此答案

于 2008-09-29T23:41:22.830 回答
203

使用日期时间的力量:

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
于 2008-09-29T23:41:59.710 回答
48

离圣诞节还有几天:

>>> import datetime
>>> today = datetime.date.today()
>>> someday = datetime.date(2008, 12, 25)
>>> diff = someday - today
>>> diff.days
86

更多的算术在这里

于 2008-09-29T23:43:01.937 回答
20

你想要 datetime 模块。

>>> from datetime import datetime, timedelta 
>>> 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 

正如这里所指出的

于 2008-09-29T23:43:10.300 回答
19

每个人都用日期回答得很好,让我尝试用熊猫回答

dt = pd.to_datetime('2008/08/18', format='%Y/%m/%d')
dt1 = pd.to_datetime('2008/09/26', format='%Y/%m/%d')

(dt1-dt).days

这将给出答案。如果输入之一是数据框列。只需使用dt.days代替days

(dt1-dt).dt.days
于 2019-11-13T06:22:05.673 回答
16
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)
于 2012-04-26T10:58:02.887 回答
12

它也可以通过以下方式轻松完成arrow

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/

于 2017-05-11T18:35:15.533 回答
9

不使用 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()
于 2018-02-05T22:37:00.863 回答
6

还有一种datetime.toordinal()方法还没有提到:

import datetime
print(datetime.date(2008,9,26).toordinal() - datetime.date(2008,8,18).toordinal())  # 39

https://docs.python.org/3/library/datetime.html#datetime.date.toordinal

date.序数()

返回日期的预测公历序数,其中第 1 年的 1 月 1 日的序数为 1。对于任何date对象ddate.fromordinal(d.toordinal()) == d.

似乎很适合计算天数差异,尽管不如timedelta.days.

于 2019-06-09T14:03:16.917 回答
5

对于计算日期和时间,有几个选项,但我会写一个简单的方法:

from datetime import timedelta, datetime, date
import dateutil.relativedelta

# current time
date_and_time = datetime.now()
date_only = date.today()
time_only = datetime.now().time()

# calculate date and time
result = date_and_time - timedelta(hours=26, minutes=25, seconds=10)

# calculate dates: years (-/+)
result = date_only - dateutil.relativedelta.relativedelta(years=10)

# months
result = date_only - dateutil.relativedelta.relativedelta(months=10)

# days
result = date_only - dateutil.relativedelta.relativedelta(days=10)

# calculate time 
result = date_and_time - timedelta(hours=26, minutes=25, seconds=10)
result.time()

希望能帮助到你

于 2018-01-31T10:53:46.613 回答
3

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+'.

于 2016-04-15T14:50:41.070 回答
3

以下是解决此问题的三种方法:

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
于 2018-03-20T13:29:28.427 回答
1

如果您想自己编写计算代码,那么这里有一个函数将返回给定年、月和日的序数:

def ordinal(year, month, day):
    return ((year-1)*365 + (year-1)//4 - (year-1)//100 + (year-1)//400
         + [ 0,31,59,90,120,151,181,212,243,273,304,334][month - 1]
         + day
         + int(((year%4==0 and year%100!=0) or year%400==0) and month > 2))

date.toordinal该函数与datetime 模块中的方法兼容。

您可以获得两个日期之间的差异天数,如下所示:

print(ordinal(2021, 5, 10) - ordinal(2001, 9, 11))
于 2021-05-10T16:29:04.207 回答
0

在 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")
于 2020-07-26T03:00:11.510 回答