agyanadda@gmail.com

Python Date and Time

Advanced Python 1 min read Updated Dec 4, 2026 Topic 27 of 32

The datetime module handles dates and times.

Current date and time

date.today(), datetime.now().

Create

date(2026, 12, 25), datetime(2026, 12, 25, 18, 30).

Parts

.year, .month, .day, .hour, .minute, .weekday() (Monday = 0).

Formatting — strftime

dt.strftime("%d %B %Y, %I:%M %p") → 25 December 2026, 06:30 PM

Code Meaning
%d %m %Y day, month, year
%B / %b month name / short
%A weekday name
%H %I %M %p 24h hour, 12h hour, minute, AM/PM

Parsing — strptime

datetime.strptime("03-12-2026", "%d-%m-%Y") turns text into a datetime.

Date maths — timedelta

today + timedelta(days=30); subtracting two dates gives a timedelta with .days.

Time zones

from zoneinfo import ZoneInfo → datetime.now(ZoneInfo("Asia/Kolkata")). Store times in UTC and convert for display. (On Windows you may need pip install tzdata.)

isoformat() gives a standard string for APIs: 2026-12-03T22:30:00+05:30.

Example

Example — Due dates and ages Python
from datetime import date, datetime, timedelta
from zoneinfo import ZoneInfo

today = date(2026, 12, 3)
due = today + timedelta(days=15)
print("Due:", due.strftime("%d %b %Y (%A)"))

exam = date(2027, 3, 1)
print("Days to exam:", (exam - today).days)

born = datetime.strptime("15-08-2004", "%d-%m-%Y").date()
age = today.year - born.year - ((today.month, today.day) < (born.month, born.day))
print("Age:", age)

meeting = datetime(2026, 12, 3, 17, 0, tzinfo=ZoneInfo("Asia/Kolkata"))
print(meeting.isoformat())
print("London:", meeting.astimezone(ZoneInfo("Europe/London")).strftime("%I:%M %p"))

Output: Due: 18 Dec 2026 (Friday), Days to exam: 88, Age: 22, 2026-12-03T17:00:00+05:30, London: 11:30 AM

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which method turns a datetime into formatted text?

Exercise 2 True / False

Subtracting two dates gives a timedelta.

Exercise 3 Fill in the Blank

Add 7 days: today + ___(days=7)

Frequently Asked Questions

strftime = string FORMAT time: datetime to text. strptime = string PARSE time: text to datetime. Remember f for format and p for parse.