DEV Community

Mate Technologies
Mate Technologies

Posted on

Building a Calendar-Accurate Date Difference Calculator with Tkinter

In this tutorial, we’ll create a desktop app using Python that calculates the exact difference between two dates in years, months, and days. We’ll use Tkinter for the GUI and dateutil for accurate date calculations.

Step 1: Importing Libraries

First, we need to import all the necessary libraries.

import sys
import os
import tkinter as tk
from tkinter import messagebox
from datetime import date
from tkcalendar import DateEntry
from dateutil.relativedelta import relativedelta
Enter fullscreen mode Exit fullscreen mode

Explanation:

tkinter → for building the GUI.

tkcalendar.DateEntry → a calendar picker for selecting dates.

dateutil.relativedelta → calculates differences in years, months, days (more accurate than just subtracting dates).

sys and os → to handle resource paths if you bundle the app.

Step 2: Defining a Theme

To make our app visually appealing, we define some colors and fonts.

APP_BG = "#121212"
PANEL_BG = "#1F1F1F"
BTN_BG = "#2C2C2C"
ACCENT = "#FF6F61"
TEXT_CLR = "#E0E0E0"
SUBTEXT_CLR = "#AAAAAA"

FONT = ("Segoe UI", 11)
Enter fullscreen mode Exit fullscreen mode

Explanation:

APP_BG, PANEL_BG, etc. → colors for different parts of the app.

FONT → defines the font used throughout the app.

This makes your GUI modern and consistent.

Step 3: Handling Resource Paths

If you later package your app with PyInstaller, you need a function to get correct file paths.

def resource_path(file_name):
    base_path = getattr(sys, "_MEIPASS", os.path.dirname(os.path.abspath(__file__)))
    return os.path.join(base_path, file_name)
Enter fullscreen mode Exit fullscreen mode

Explanation:

Ensures the app can find images or resources both in development and packaged mode.

Step 4: Date Calculation Logic

Here’s the function that calculates the difference between two dates.

def calculate_exact_difference(d1, d2):
    if d2 < d1:
        d1, d2 = d2, d1  # Swap dates if the first is later

    delta = relativedelta(d2, d1)
    total_days = (d2 - d1).days

    return {
        "Years": delta.years,
        "Months": delta.months,
        "Days": delta.days,
        "Total Days": total_days
    }
Enter fullscreen mode Exit fullscreen mode

Explanation:

relativedelta gives calendar-accurate differences (handles months and leap years correctly).

total_days is a simple subtraction for total day difference.

Swapping ensures the earlier date is first, avoiding negative numbers.

Step 5: Creating the GUI Class

We’ll use a class to structure our Tkinter app.

class DateDifferenceCalculator:
    def __init__(self, root):
        self.root = root
        root.title("MateTools – Date Difference Calculator")
        root.geometry("1000x520")
        root.configure(bg=APP_BG)
        root.resizable(False, False)
Enter fullscreen mode Exit fullscreen mode

Explanation:

root.title → sets window title.

root.geometry → sets window size.

root.configure → sets background color.

root.resizable(False, False) → prevents resizing.

Step 6: Left Panel with Date Pickers

We create a panel where the user selects two dates.

left = tk.Frame(root, bg=PANEL_BG, width=420)
left.pack(side="left", fill="y")

tk.Label(left, text="Select Dates", bg=PANEL_BG, fg=TEXT_CLR, font=("Segoe UI", 12, "bold")).pack(anchor="w", padx=12, pady=(14, 6))

self.date1 = DateEntry(left, background=BTN_BG, foreground=TEXT_CLR, borderwidth=0, font=FONT, date_pattern="yyyy-mm-dd")
self.date1.pack(fill="x", padx=12, pady=8)

self.date2 = DateEntry(left, background=BTN_BG, foreground=TEXT_CLR, borderwidth=0, font=FONT, date_pattern="yyyy-mm-dd")
self.date2.pack(fill="x", padx=12, pady=8)
Enter fullscreen mode Exit fullscreen mode

Explanation:

tk.Frame → creates a panel on the left side.

DateEntry → a calendar widget for selecting dates.

pack() → positions the widgets.

Step 7: Adding Buttons

btn_frame = tk.Frame(left, bg=PANEL_BG)
btn_frame.pack(fill="x", padx=12, pady=14)

def make_btn(text, cmd, color=BTN_BG):
    return tk.Button(btn_frame, text=text, command=cmd, bg=color, fg="white", font=("Segoe UI", 11, "bold"), relief="flat", height=2, width=20)

make_btn("Calculate", self.calculate).pack(side="left", expand=True, padx=4)
make_btn("About", self.show_about, ACCENT).pack(side="left", expand=True, padx=4)
Enter fullscreen mode Exit fullscreen mode

Explanation:

make_btn() → helper function to create buttons with consistent style.

Buttons:

Calculate → computes date difference.

About → shows app information.

Step 8: Right Panel with Results

right = tk.Frame(root, bg=APP_BG)
right.pack(side="right", fill="both", expand=True)

tk.Label(right, text="MateTools", bg=APP_BG, fg=ACCENT, font=("Segoe UI", 22, "bold")).pack(anchor="w", padx=30, pady=(24, 2))
tk.Label(right, text="Date Difference Calculator", bg=APP_BG, fg=TEXT_CLR, font=("Segoe UI", 14, "bold")).pack(anchor="w", padx=30)
tk.Label(right, text="Calendar-accurate years, months, and days", bg=APP_BG, fg=SUBTEXT_CLR, font=("Segoe UI", 10)).pack(anchor="w", padx=30, pady=(0, 18))
Enter fullscreen mode Exit fullscreen mode

Explanation:

Displays app name, tool name, and description.

Helps users understand what the tool does.

Step 9: Creating the Stats Card

stats_card = tk.Frame(right, bg=PANEL_BG)
stats_card.pack(padx=30, pady=10, fill="both", expand=True)

tk.Label(stats_card, text="Exact Date Difference", bg=PANEL_BG, fg=TEXT_CLR, font=("Segoe UI", 14, "bold")).pack(pady=(20, 10))

self.stats = {}
for label in ["Years", "Months", "Days", "Total Days"]:
    frame = tk.Frame(stats_card, bg=PANEL_BG)
    frame.pack(fill="x", padx=40, pady=6)
    tk.Label(frame, text=label, bg=PANEL_BG, fg=SUBTEXT_CLR, font=("Segoe UI", 11)).pack(side="left")
    value = tk.Label(frame, text="0", bg=PANEL_BG, fg="white", font=("Segoe UI", 12, "bold"))
    value.pack(side="right")
    self.stats[label] = value
Enter fullscreen mode Exit fullscreen mode

Explanation:

Displays results dynamically.

Each row shows Years, Months, Days, and Total Days.

self.stats stores label references for easy updating.

Step 10: Button Methods

def calculate(self):
    d1 = self.date1.get_date()
    d2 = self.date2.get_date()
    result = calculate_exact_difference(d1, d2)
    for key, value in result.items():
        self.stats[key].config(text=str(value))

def show_about(self):
    messagebox.showinfo(
        "About",
        "MateTools – Date Difference Calculator\n\n"
        "• Calendar picker input\n"
        "• Calendar-accurate calculations\n"
        "• Leap years supported\n\n"
        "Built by MateTools"
    )
Enter fullscreen mode Exit fullscreen mode

Explanation:

calculate() → fetches dates and updates result labels.

show_about() → shows an info popup.

Step 11: Running the App

if __name__ == "__main__":
    root = tk.Tk()
    DateDifferenceCalculator(root)
    root.mainloop()
Enter fullscreen mode Exit fullscreen mode

Explanation:

Standard Tkinter entry point.

Creates the main window and runs the app.

✅ Result:
You now have a beautiful desktop app that calculates calendar-accurate date differences, supports leap years, and looks modern with a dark theme.

Date Difference Calculator

Top comments (0)