Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Tkinter-How to get the current date to display in a tkinter window?
To display the current date in a Tkinter window, we can use Python's built-in datetime module to get the current date and time, then format it for display in a Label widget.
Basic Approach
The key steps are importing datetime, getting the current date with datetime.now(), and formatting it using strftime format codes ?
import tkinter as tk
import datetime as dt
# Get current date
current_date = dt.datetime.now()
print(f"Today is: {current_date:%A, %B %d, %Y}")
Today is: Wednesday, December 18, 2024
Complete Tkinter Example
Here's a complete example that creates a window displaying the current date ?
import tkinter as tk
import datetime as dt
# Create main window
root = tk.Tk()
root.title("Current Date Display")
root.geometry("400x200")
root.configure(bg="lightblue")
# Get current date
current_date = dt.datetime.now()
# Create and configure label
date_label = tk.Label(
root,
text=f"{current_date:%A, %B %d, %Y}",
font=("Arial", 16, "bold"),
bg="lightblue",
fg="darkblue"
)
date_label.pack(pady=50)
# Start the GUI event loop
root.mainloop()
Date Format Codes
The format string uses specific codes to display different parts of the date ?
| Format Code | Description | Example |
|---|---|---|
%A |
Full weekday name | Wednesday |
%B |
Full month name | December |
%d |
Day of the month (01-31) | 18 |
%Y |
Year with century | 2024 |
Alternative Date Formats
You can customize the date format according to your needs ?
import datetime as dt
current_date = dt.datetime.now()
# Different format styles
formats = [
f"{current_date:%m/%d/%Y}", # 12/18/2024
f"{current_date:%d-%b-%Y}", # 18-Dec-2024
f"{current_date:%B %d, %Y}", # December 18, 2024
f"{current_date:%a, %d %b %Y}" # Wed, 18 Dec 2024
]
for i, date_format in enumerate(formats, 1):
print(f"Format {i}: {date_format}")
Format 1: 12/18/2024 Format 2: 18-Dec-2024 Format 3: December 18, 2024 Format 4: Wed, 18 Dec 2024
Conclusion
Use datetime.now() to get the current date and format it with strftime codes like %A, %B, %d, and %Y. Display it in a Tkinter Label widget with appropriate styling for a clean user interface.
