在 python 中找出所选日期和当前日期之间的差异(以天为单位)

Find the difference between the chosen date and current date in python (in Days)

I want to choose the day from tkcalendar and find the difference between the chosen date and the current date.Can anyone help? (as simple as possible) Also, I tried have installed tkcalendar and I can use it but vscode says report missing import

newToProgramming 无法从其他

from tkinter import *
try :
    from tkcalendar import *
except:
    pass

root = Tk()  # Creating instance of Tk class
root.title("Centering windows")
root.resizable(False, False)  # This code helps to disable windows from resizing

root.geometry("200x200+600+100")

def days():
    # find the difference between the current date and the choosen date
    pass

Label(root, text= 'Pick Up Date :').pack()
txt_pdate = DateEntry(root)
txt_pdate.pack()

txt_pdate.get_date()

btn = Button(root, text='click', command= days).pack()


root.mainloop()

我会使用内置的 python 模块 datetime。

from datetime import date,datetime

d0 = datetime.today()
d1 = date(2008, 9, 26)
delta = d1 - d0
print(delta.days)

只需安装 python-dateutil


pip3 install python-dateutil # or pip install python-dateutil

然后:


...

from dateutil.relativedelta import relativedelta
from datetime import datetime as dt
...

difference = relativedelta(txt_pdate.get_date(), dt.today())

# you will have access to years, months, days

print(f'years:{difference.years}, months:{difference.months}, days:{difference.days}')


这是我想出的一个有点乱的应用程序,你会得到大致的想法



from tkinter import Tk
from tkinter import Label
from tkinter import Toplevel
from tkinter import Button
from tkcalendar import DateEntry
from datetime import datetime
from datetime import date
from dateutil.relativedelta import relativedelta


root = Tk()
root.title("Date picker")
root.geometry("1000x800")

currentDate = Label(root, text="current date: " + datetime.now().strftime('%Y/%m/%d'), pady=50, padx=50)
currentDate.pack()



dateInput = DateEntry(root)
dateInput.pack()


def destroyPopop(window):
    window.destroy()


def calDiffence():

    out = relativedelta( dateInput.get_date(), date.today())

    return out


def popupWindow():
    popup = Toplevel(root)
    popup.title('date difference')
    popup.geometry("400x400")
    data = calDiffence()
    diffOutput = Label(popup, text=f'years:{data.years}, months:{data.months}, days:{data.days}')
    diffOutput.pack()

    okButton = Button(popup, text="OK", command=lambda:destroyPopop(popup), pady=100, padx=100)
    okButton.pack()

    popup.pack()


calcucate = Button(root, text="difference between the chosen date and the current date", command=popupWindow)
calcucate.pack(pady=20)


root.mainloop()