🟡 Advanced Python · Lesson 24
Date and Time Handling
The datetime Module
Python's built-in datetime module handles dates and times — getting the current date, formatting it, and calculating differences between dates.
Current Date & Time
Python – now.py
from datetime import datetime
now = datetime.now()
print("Now :", now)
print("Year :", now.year)
print("Month :", now.month)
print("Day :", now.day)Now : 2026-06-01 11:56:00
Year : 2026
Month : 6
Day : 1
Formatting with strftime
strftime() turns a date into a nicely formatted string.
| Code | Means |
|---|---|
| %d | day (01-31) |
| %m | month (01-12) |
| %Y | year (2026) |
| %H:%M | hour:minute |
| %A | weekday name |
Program 1: Today in Different Formats
Python – today.py
from datetime import datetime
today = datetime.now()
print(today.strftime("%d/%m/%Y"))
print(today.strftime("%A, %d %B %Y"))
print(today.strftime("Time: %H:%M"))01/06/2026
Monday, 01 June 2026
Time: 11:56
Program 2: Age Calculator
Python – age.py
from datetime import date
birth = date(2008, 5, 15)
today = date.today()
age = today.year - birth.year
# adjust if birthday has not happened yet this year
if (today.month, today.day) < (birth.month, birth.day):
age -= 1
print("Age:", age, "years")Age: 18 years
Subtracting years gives a rough age; the if corrects it if the birthday has not occurred yet this year.
Program 3: Days Until a Date
Python – countdown.py
from datetime import date
exam = date(2026, 12, 1)
today = date.today()
diff = exam - today
print("Days until exam:", diff.days)Days until exam: 183
Subtracting two dates gives a timedelta; .days reads the number of days.
Common Mistakes
- Confusing
date(just date) withdatetime(date + time). - Wrong strftime codes (e.g.
%Mis minute,%mis month). - Forgetting to import:
from datetime import datetime.
Practice Tasks
- Print today's date as "Day-Month-Year".
- Calculate how many days you have been alive.
- Print the current weekday name.
- Count the days left until your next birthday.
Summary
- The
datetimemodule handles dates and times. datetime.now()/date.today()get the current moment.strftime()formats dates; subtracting dates gives day differences.
💻 Live Code Editor
This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.