🟡 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.

CodeMeans
%dday (01-31)
%mmonth (01-12)
%Yyear (2026)
%H:%Mhour:minute
%Aweekday 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) with datetime (date + time).
  • Wrong strftime codes (e.g. %M is minute, %m is month).
  • Forgetting to import: from datetime import datetime.

Practice Tasks

  1. Print today's date as "Day-Month-Year".
  2. Calculate how many days you have been alive.
  3. Print the current weekday name.
  4. Count the days left until your next birthday.

Summary

  • The datetime module handles dates and times.
  • datetime.now() / date.today() get the current moment.
  • strftime() formats dates; subtracting dates gives day differences.
← Back to Python Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 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.