简体   繁体   English

两个日期之间的Python差异

[英]Python difference between two dates

For some reason I'm really stumped with this (relativity) question. 由于某种原因,我真的为这个(相对性)问题感到困惑。

How to calculate the difference between two dates. 如何计算两个日期之间的差异。 I want to do this without using modules. 我想这样做而不使用模块。 But for some reason my code isn't outputting the correct answer. 但是由于某种原因,我的代码没有输出正确的答案。

This is my thought process: 这是我的思考过程:

If asked calculate the # of days between Dec 10th 2014 and Feb 2nd 2015. 如果需要,请计算2014年12月10日至2015年2月2日之间的天数。

  1. First find the number of days left in Dec from the 10th on (31 - 10) = 21 days 首先找到(31-10)的10日从12月剩下的天数= 21天

  2. Find the number of months between Dec and Feb ( aka Jan) add the number days in that month = 31 days 找出12月至2月(又称1月)之间的月数,加上该月的天数= 31天

  3. Add the Days left in Dec (21) + the days in between the months (31) + the days in the last month (2) = 54 days. 加上12月(21)剩下的天数+月份之间的天数(31)+上个月的天数(2)= 54天。

  4. Then check for anomalies ie Leap Year etc. 然后检查异常,例如Le年等。

This is my function: 这是我的功能:

def Calculate_Date (year1, month1, day1, year2, month2, day2):
"""
This function takes to dates (year/month/day) and returned the
difference between the dates
"""

#Create a dict for the # of days in each month
month_days = {1:31,2:28,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31}

days_left_in_month1 = month_days[month1] - day1
days_left_in_year1 =0 
days_into_year2 =0
days_between_year1_and_year2= 0
difference_in_days = 0

# Find the number days left in year one
i = month1
days_left_in_year = []
while i <= 12:
    days = month_days[i]
    days_left_in_year.append(days)
    i = i + 1

days_left_in_year1 = (sum(days_left_in_year)) - day1

# Find the number days into year two
i = 1
days_into_year = []
while i <= month2:
    days = month_days[i]
    days_into_year.append(days)
    i = i + 1
days_into_year2 = sum(days_into_year) - day2

#find the differernce in years 
days_between_year1_and_year2 = (year2 - year1) * 365


#Check if its a leap year
leap_year = False
while True:
    if float(year1 % 4) == 0:
        if float(year1 % 100) != 0:
                leap_year = True
                break
        if float(year1 % 100) == 0:
            if float(year1 % 400) ==0:
                leap_year = True
                break               
    else:
        break

#test output
print "The number of days left in the year One are %r " % days_left_in_year1
print "The number of days into the year Two are %r "    % days_into_year2
print "The number of days between the years are %r "    % days_between_year1_and_year2

#add an increment if leap year was true
if leap_year == True:
    difference_in_days = days_left_in_year1 + days_into_year2 + days_between_year1_and_year2 + 1

else:
    difference_in_days = days_left_in_year1 + days_into_year2 + days_between_year1_and_year2

return difference_in_days


print Calculate_Date(2011,6,30,2012,06,30)

Instead of doing date2 - date1 , you might find it simpler to do (date2 - x) - (date1 - x) where x is an easy-to-handle date, ie "Jan 0" of year1 . 与执行date2 - date1 ,您可能会发现它更容易执行(date2 - x) - (date1 - x) ,其中x是易于处理的日期,即year1 “ Jan 0”。


Let's define a couple of functions: 让我们定义几个函数:

def days_in_month(year, month):
    """
    Return number of days in the specified month (28, 29, 30, or 31)
    """
    if month == 2:    # February
        if not (year % 400):
            return 29
        elif not (year % 100):
            return 28
        elif not (year % 4):
            return 29
        else:
            return 28
    elif month in {1, 3, 5, 7, 8, 10, 12}:
        return 31
    else:
        return 30

def days_in_year(year):
    """
    Return the number of days in the specified year (365 or 366)
    """
    return 337 + days_in_month(year, 2)

def days_this_year(year, month, day):
    """
    Return the number of days so far this year
    """
    return sum(days_in_month(year, m) for m in range(1, month)) + day

def year_days_since(base_year, this_year):
    """
    Return the number of days from the start of base_year to the start of this_year
    """
    if base_year > this_year:
        raise ValueError("base_year must be <= this_year")
    elif base_year == this_year:
        return 0
    else:
        return sum(days_in_year(y) for y in range(base_year, this_year))

then the difference between two dates becomes: 那么两个日期之间的差变为:

def date_diff(y1, m1, d1, y2, m2, d2):
    x = min(y1, y2)   # base date
    days1 = year_days_since(x, y1) + days_this_year(y1, m1, d1)
    days2 = year_days_since(x, y2) + days_this_year(y2, m2, d2)
    return days2 - days1

and because of the symmetry in this answer it will also happily do negative differences: 由于此答案的对称性,它也会很高兴地带来负面影响:

date_diff(2001, 1, 3, 2002, 2, 5)   # =>  398 == 365 + 31 + 2
date_diff(2002, 2, 5, 2001, 1, 3)   # => -398

In case this is a real code, and not a school assignment, this is the way I'd do it: 如果这是一个真实的代码,而不是学校的作业,这就是我要做的方式:

from datetime import date

def date_diff(y1, m1, d1, y2, m2, d2):
    return (date(y2, m2, d2) - date(y1, m1, d1)).days

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM