Python provides the datetime module to work with dates and times. It allows you to get the current date and time, format dates, and perform date calculations.
Get Current Date and Time
Example
import datetime
current = datetime.datetime.now()
print(current)
Output:
2026-05-31 14:30:45.123456
Output will vary based on the current date and time.
Get Current Date
Example
import datetime
today = datetime.date.today()
print(today)
Output:
2026-05-31
Get Current Time
Example
import datetime
current_time = datetime.datetime.now().time()
print(current_time)
Output:
14:30:45.123456
Create a Specific Date
Example
import datetime
date = datetime.datetime(2026, 5, 31)
print(date)
Output:
2026-05-31 00:00:00
Display Year, Month, and Day
Example
import datetime
today = datetime.datetime.now()
print(today.year)
print(today.month)
print(today.day)
Output:
2026
5
31
Format Date Using strftime()
The strftime() method formats date and time into a readable string.
Example
import datetime
today = datetime.datetime.now()
print(today.strftime("%d-%m-%Y"))
Output:
31-05-2026
Common Format Codes
| Code | Description | Example |
|---|---|---|
%d | Day | 31 |
%m | Month | 05 |
%Y | Year | 2026 |
%H | Hour (24-hour) | 14 |
%M | Minute | 30 |
%S | Second | 45 |
%A | Weekday Name | Sunday |
%B | Month Name | May |
Get Weekday Name
Example
import datetime
today = datetime.datetime.now()
print(today.strftime("%A"))
Output:
Sunday
Date Difference
Example
import datetime
date1 = datetime.date(2026, 5, 1)
date2 = datetime.date(2026, 5, 31)
difference = date2 - date1
print(difference.days)
Output:
30
Summary
- Python uses the
datetimemodule for date and time operations. datetime.now()returns the current date and time.date.today()returns the current date.strftime()formats dates and times.- Individual components like year, month, and day can be accessed separately.
- Dates can be compared and subtracted to find differences.