时间数据不匹配格式 Python 错误

Time Data Does Not Match Format Python Error

我正在尝试获取用户选择的日期与今天之间的天数。尝试 运行 时出现此错误:

raise ValueError("time data %r does not match format %r" %
ValueError: time data '1/28/21' does not match format '%m %d %y'

我是 python 的新手,非常感谢任何能为我指明正确方向的帮助!

# Import Required Library
from tkinter import *
from tkcalendar import Calendar
from datetime import datetime, timedelta

today = datetime.today()

# Create Object
root = Tk()

# Set geometry
root.geometry("500x800")

# Add Entry Box for token goal amount
instructions1 = Label(text="Please input your goal amount for the pay period.")
instructions1.pack(pady=10)

tokenGoal = Entry(root)
tokenGoal.pack(pady=10)

instructions2 = Label(text="Please enter the amount you currently have")
instructions2.pack(pady=10)

tokenAmount = Entry(root)
tokenAmount.pack(pady=10)

instructions3 = Label(text=today)
instructions3.pack()

print(today)

# Add Calender
cal = Calendar(root, selectmode='day',
               month=1, day=22,
               year=2021)

cal.pack(pady=20)


def grad_date():
    date.config(text="Selected Date is: " + cal.get_date())
    find_days_left()


def find_days_left():
    selected_date = datetime.strptime(cal.get_date(), '%m %d  %y')
    days_left = selected_date - today
    instructions3.config(text=today)


# Add Button and Label
Button(root, text="Calculate Pay Period",
       command=grad_date).pack(pady=20)

date = Label(root, text="")
date.pack(pady=20)

# Excecute Tkinter
root.mainloop()

您的错误似乎在这里:

    selected_date = datetime.strptime(cal.get_date(), '%m %d  %y')
    days_left = selected_date - today
    instructions3.config(text=today)

日期格式应该是 "%m/%d/%y" 请注意分隔值的斜杠而不是空格。

你为什么不试试这个,如果这是你想要的..

   f_date = date(2005, 11, 7)
   l_date = date(2021, 3, 13)
   delta = (l_date - f_date)
   print(delta.days)}