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
How to insert the current time in an Entry Widget in Tkinter?
To work with the date and time module, Python provides the datetime package. Using the datetime package, we can display the current time, manipulate datetime objects and use them to add functionality in Tkinter applications.
To display the current time in an Entry widget, we first import the datetime module and create an instance of its object. The Entry widget can then display this formatted time information ?
Basic Example − Current Date
Here's how to display the current date in an Entry widget ?
# Import the required libraries
from tkinter import *
import datetime as dt
# Create an instance of tkinter frame or window
win = Tk()
# Set the size of the tkinter window
win.geometry("700x350")
win.title("Current Date Display")
# Create an instance of datetime module
date = dt.datetime.now()
# Format the date
format_date = f"{date:%a, %b %d %Y}"
# Display the date in an Entry widget
entry = Entry(win, width=25, font=("Calibri", 25))
entry.insert(END, format_date)
entry.pack(pady=20)
win.mainloop()
Displaying Current Time
To show the current time instead of just the date ?
from tkinter import *
import datetime as dt
# Create tkinter window
win = Tk()
win.geometry("700x350")
win.title("Current Time Display")
# Get current time
current_time = dt.datetime.now()
# Format the time
format_time = f"{current_time:%H:%M:%S %p}"
# Display in Entry widget
entry = Entry(win, width=25, font=("Calibri", 25))
entry.insert(END, format_time)
entry.pack(pady=20)
win.mainloop()
Complete Date and Time
To display both date and time together ?
from tkinter import *
import datetime as dt
# Create tkinter window
win = Tk()
win.geometry("700x400")
win.title("Current Date and Time")
# Get current datetime
now = dt.datetime.now()
# Format complete datetime
format_datetime = f"{now:%Y-%m-%d %H:%M:%S}"
# Display in Entry widget
entry = Entry(win, width=30, font=("Arial", 20))
entry.insert(END, format_datetime)
entry.pack(pady=20)
# Add a label for context
label = Label(win, text="Current Date and Time:", font=("Arial", 14))
label.pack(pady=10)
win.mainloop()
Common Time Formats
| Format Code | Description | Example |
|---|---|---|
%Y-%m-%d |
YYYY-MM-DD | 2024-03-15 |
%H:%M:%S |
24-hour time | 14:30:25 |
%I:%M %p |
12-hour time | 02:30 PM |
%a, %b %d %Y |
Weekday, Month Date Year | Fri, Mar 15 2024 |
Conclusion
Use datetime.now() to get the current time and format it with f-strings. Insert the formatted time into an Entry widget using the insert() method with END parameter.
