两个日期python之间的差异

时间:2014-11-01 16:04:55

标签: python python-3.x

from datetime import date
future = input("Enter a date(dd/mm/yyyy): ")
daystring = future[0:2]
monthstring = future[3:5]
yearstring = future[6:10]

today = (date.today())
month = date.today().month
year = date.today().year
day = date.today().day

if monthstring  == "01" or "03" or "05" or "07" or "08" or "10" or "12":
    if daystring > "31":
        print("Invalid Date Entered")
if monthstring == "04" or "06" or "09" or "11":
    if daystring > "30":
        print("Invalid Date Entered")
months = ["Jan", "Feb", "Mar", "Apr", "May", "June",
          "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
daysinmonth = [31, 29, 31, 30, 31, 30, 31, 31, 30,
               31, 30, 31]


if future < today or monthstring > "12":
    print("Invalid Date Entered")

else:
    layout = "%d/%m/%Y"
    a = datetime.strptime(future, layout)
    b = datetime.strptime(today, layout)
    delta = a - b
    print ("The difference between the inputted date and todays date is: ",delta.days, "days")

此代码是要求用户在将来输入日期,然后代码应使用该输入并从中减去当前日期。

例如,今天是2014年11月1日,如果用户输入03/11/2014,则输出应为差异为2天。

但是,每次输入未来日期时,我都会收到错误消息。

2 个答案:

答案 0 :(得分:0)

import dateutil.parser as parser
import datetime
date1 = parser.parse(input("Enter Date:"))
print( (datetime.datetime.now() - date1).days )

dateutil非常擅长解析自然日期字符串......

您可能需要安装dateutil

easy_install python-dateutil

如果您不想使用提到的dateutil,可以使用strptime

def get_user_date(prompt="Enter Date:"):
    while True:
       try:
          return datetime.datetime.strptime("%m/%d/%y",input(prompt)) 
       except ValueError:
          print( "Invalid Input!" )

我认为这段代码可以在python 3中运行

答案 1 :(得分:-1)

有不同的事情需要考虑。试着考虑这些要点

  • 检查用户是否输入了正确的日期时间。您可以使用正则表达式来执行此操作。您可以使用RE模块。
mat=re.match('(\d{2})[/](\d{2})[/](\d{4})$', str(future))
  • 您应该在1-12之间过滤数月,在1-31之间过滤数天。然后区分几个月,并且在两种情况下都不要忘记February(闰年或否)。您可以使用calender模块进行检查。
t= calendar.monthrange(int(yearstring), 2) # This is to check if February has 29 or 28 (is leap year or no), you can do that by checking the day number of "datetime.date (int(yearstring), 3, 1) - datetime.timedelta (days = 1)"
  • 然后,比较两个日期,您应该为每个日期使用正确的时间格式。
 a = date.datetime.strptime(future, "%d/%m/%Y").date()
 b = date.datetime.strptime(today, "%Y-%m-%d").date()
 delta = a-b

您的代码如下:

import datetime as date
import re
import calendar

future = input("Enter a date(dd/mm/yyyy): ")
#eg: future="02/03/2015"
#print future

mat=re.match('(\d{2})[/](\d{2})[/](\d{4})$', str(future))
if mat is None:
    print("Invalid Date Entered, try to enter a date in this form(dd/mm/yyyy) ")
else: 
    daystring,monthstring,yearstring= mat.groups()

    today= str(date.datetime.now()).split(" ")[0]
    year, month, day = today.split("-")

    months = ["Jan", "Feb", "Mar", "Apr", "May", "June","Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
    daysinmonth = [31, 29, 31, 30, 31, 30, 31, 31, 30,31, 30, 31]

    if int(daystring)>0 and int(daystring)<=31 and int(monthstring)>0 and int(monthstring) <= 12 and int(yearstring)>0:
        if monthstring  in ["01", "03", "05" ,"07","08","10", "12"]:
            if int(daystring) > 31:
                print("Invalid Date Entered - Number of days can't exceed 31.")
        if monthstring in ["04","06","09","11"]:
            if int(daystring) > 30:
                print("Invalid Date Entered - Number of days can't exceed 31.")
        if monthstring == "02":
            t= calendar.monthrange(int(yearstring), 2) # This is to check if February has 29 or 28 (is leap year or no), you can do that by checking the day number of "datetime.date (int(yearstring), 3, 1) - datetime.timedelta (days = 1)" 
            if int(daystring) !=t: #You forget faberuary 
                print("Invalid Date Entered - of days can't exceed 28 or 29")


        a = date.datetime.strptime(future, "%d/%m/%Y").date()
        b = date.datetime.strptime(today, "%Y-%m-%d").date()
        delta = a-b   # The future - Today ::> to get a positive number 
        if delta.days >0:
            print ("The difference between the inputted date and todays date is: ",delta.days, "days")
        else:
            print("Date is in the past")

    else: 
        print("Invalid Date Entered")