只需安装 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()