Date and Time Module in Python
Python provides built-in modules to work with date and time. The most commonly used modules are:
-
datetimemodule – used to work with dates and times. -
timemodule – used for time-related functions such as delays and timestamps.
1. datetime Module
The datetime module helps to get the current date, time, and perform date calculations.
Importing the module
import datetime
Example: Display Current Date and Time
import datetime
now = datetime.datetime.now()
print("Current Date and Time:", now)
Output (example):
Current Date and Time: 2026-03-09 10:30:15.234567
Example: Display Only Current Date
from datetime import date
today = date.today()
print("Today's Date:", today)
Output:
Today's Date: 2026-03-09
Example: Formatting Date and Time
from datetime import datetime
now = datetime.now()
formatted = now.strftime("%d-%m-%Y %H:%M:%S")
print("Formatted Date and Time:", formatted)
Output:
Formatted Date and Time: 09-03-2026 10:35:20
Common Format Codes:
| Code | Meaning |
|---|---|
%d | Day |
%m | Month |
%Y | Year |
%H | Hour |
%M | Minute |
%S | Second |
2. time Module
The time module is used for time operations and program delays.
Importing the module
import time
Example: Display Current Time
import time
print("Current Time:", time.ctime())
Output:
Current Time: Mon Mar 9 10:40:25 2026
Example: Pause Execution using sleep()
import time
print("Start")
time.sleep(3)
print("End after 3 seconds")
This program pauses for 3 seconds before printing the next line.
Summary Table
| Module | Function | Purpose |
|---|---|---|
| datetime | datetime.now() | Current date and time |
| datetime | date.today() | Current date |
| datetime | strftime() | Format date and time |
| time | ctime() | Display current time |
| time | sleep() | Pause program execution |
Conclusion:
The datetime and time modules help Python programs handle dates, times, formatting, and delays, which are useful in applications like scheduling, logging, and timers.
- Get link
- X
- Other Apps
- Get link
- X
- Other Apps
Comments
Post a Comment