Python using tkcalendar with if-statements

321 Views Asked by At

Im trying to make if-statements with tkcalendar but dont know why it is not working.

from tkinter import *
from tkcalendar import *
import datetime

root = Tk()
root.title('Hi')
root.geometry('500x400')

cal = Calendar(root, date_pattern="d/m/y", year = 2020, month = 11, day = 1)
cal.pack(pady=20)

def grab_date():
    my_label.config(text = cal.get_date())
    d = cal.get_date()
    print(d)
    if datetime.datetime.strptime('01/11/2020', "%d/%m/%Y").strftime("%d/%m/%Y") 
    <=d<=datetime.datetime.strptime('01/1/2021', "%d/%m/%Y").strftime("%d/%m/%Y"):
        print('ok')

my_button = Button(root, text = 'Get date', command = grab_date)
my_button.pack()

my_label = Label(root, text = ' ')
my_label.pack(pady = 20)

root.mainloop()

It does not print 'ok' when I press the button between the dates. Does anyone know how I can fix this problem and how the if-statements are done when using tkcalendar? I want to then to add more conditions of when other dates are pressed print something else.

1

There are 1 best solutions below

5
On BEST ANSWER

Consider the below example.

import datetime



def betweenDates(date,start,end):
    return (date>start) and (date<end)

start = datetime.datetime.strptime('01/11/2020', "%d/%m/%Y").date()
end = datetime.datetime.strptime('01/1/2021', "%d/%m/%Y").date()

today = datetime.datetime.now().date()

if betweenDates(today,start,end):
    print("Ok")

This will compare today's date to see if it is between two specified dates using a function (makes the if statement line shorter and the comparison reusable).

To do this with tkcalendar you need to convert the date from it to a datetime object (or since you want to remove the time, a datetime.date object)

Since tkcalendar returns a string you need to use strptime to parse it. Might look like this

d = datetime.datetime.strptime(cal.get_date(),"%d/%m/%Y").date()

Hope that helps you to get your code working

Edit: Your function may look like this. Untested however due to lack of tkcalendar installed

def grab_date():
    my_label.config(text = cal.get_date())
    d = datetime.datetime.strptime(cal.get_date(),"%d/%m/%Y").date()
    print(d)
    start = datetime.datetime.strptime('01/11/2020', "%d/%m/%Y").date()
    end = datetime.datetime.strptime('01/1/2021', "%d/%m/%Y").date()
    if betweenDates(d,start,end):
        print('ok')