Search code examples
pythonpython-3.xdatetimeruntime-error

Time Data Does Not Match Format Python Error


I am trying to get the amount of days between the date the user selects from today's day. I get this error when attempting to run it:

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

I am very new to python, so any help pointing me in the right direction is very much appreciated!

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

Solution

  • Your error appears to be here:

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

    The date format is should be "%m/%d/%y" Notice the slashes separating the values rather than spaces.