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


当前回答

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

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

此功能与日期兼容。datetime模块中的Toordinal方法。

两个日期的差日数如下所示:

print(ordinal(2021, 5, 10) - ordinal(2001, 9, 11))

其他回答

如果您有两个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 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)

# week
results = date_only - dateutil.relativedelta.relativedelta(weeks=1)

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

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

希望能有所帮助

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

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

此功能与日期兼容。datetime模块中的Toordinal方法。

两个日期的差日数如下所示:

print(ordinal(2021, 5, 10) - ordinal(2001, 9, 11))

在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")

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

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