Deadlines, birthdays, timestamps and opening hours all need dates and times. Python’s built-in datetime module creates them, formats them as text, reads them back from text, and does arithmetic such as “30 days from now” or “hours between two times”. The zoneinfo module adds proper time zones. This lesson covers all of it with tested examples.
In this lesson you will learn
- How to create
dateanddatetimeobjects - How to format them with
strftime() - How to read dates from text with
strptime() - Date arithmetic with
timedelta - How to work with time zones
Creating, Formatting and Parsing
from datetime import date, datetime, timedelta
exam = date(2026, 12, 16)
print(exam, exam.year, exam.strftime("%A"))
moment = datetime(2026, 11, 15, 19, 30)
print(moment.strftime("%d/%m/%Y %I:%M %p"))
parsed = datetime.strptime("25-12-2026 08:15", "%d-%m-%Y %H:%M")
print(parsed)
print(exam + timedelta(days=30))
gap = date(2027, 1, 1) - date(2026, 11, 15)
print(gap.days, "days")
Output
2026-12-16 2026 Wednesday
15/11/2026 07:30 PM
2026-12-25 08:15:00
2027-01-15
47 days
date(year, month, day)holds a calendar date;datetimeadds hours and minutes. Usedate.today()ordatetime.now()for the current moment.strftime()(“string format time”) turns a date into text using codes like%d.strptime()(“string parse time”) does the reverse: it reads text in a given format.- Adding a
timedeltamoves a date forward; subtracting two dates gives atimedeltawhose.daysis the gap.
Common Format Codes
| Code | Meaning | Example |
|---|---|---|
%Y / %y | Year, 4 or 2 digits | 2026 / 26 |
%m | Month number | 12 |
%B / %b | Month name, full / short | December / Dec |
%d | Day of the month | 16 |
%A / %a | Weekday, full / short | Wednesday / Wed |
%H / %I | Hour, 24-hour / 12-hour | 19 / 07 |
%M, %S | Minutes, seconds | 30, 00 |
%p | AM or PM | PM |
Time Zones and Durations
from datetime import datetime, timezone, timedelta
from zoneinfo import ZoneInfo
meeting = datetime(2026, 11, 20, 15, 0, tzinfo=ZoneInfo("Asia/Dhaka"))
print(meeting.isoformat())
print(meeting.astimezone(ZoneInfo("Europe/London")).strftime("%H:%M %Z"))
print(meeting.astimezone(timezone.utc).strftime("%H:%M UTC"))
start = datetime(2026, 11, 15, 9, 0)
end = datetime(2026, 11, 15, 17, 45)
worked = end - start
print(worked, worked.total_seconds() / 3600, "hours")
print((start + timedelta(weeks=1)).date())
Output
2026-11-20T15:00:00+06:00
09:00 GMT
09:00 UTC
8:45:00 8.75 hours
2026-11-22
ZoneInfo("Asia/Dhaka")attaches a real time zone;.isoformat()shows the offset (+06:00)..astimezone()converts the same moment to another zone: 3 pm in Dhaka is 9 am in London and in UTC in November.timedeltasupports days, hours, minutes and weeks;.total_seconds()converts a duration to a number.
Store times in UTC
A common rule for apps is to store every timestamp in UTC and convert to the user’s zone only when displaying it. That avoids daylight-saving surprises.
Common Mistakes
- Mixing up
%m(month) and%M(minute). - Comparing “naive” and “aware” datetimes (without and with a time zone), which raises
TypeError. - Adding months with
timedelta. It has no month unit because months differ in length; use thedateutilpackage for that. - Using a
strptimeformat that does not exactly match the text, which raisesValueError.
Practice Exercises
Exercise 1. Work out someone’s age in whole years from a birth date of 15 August 2004, on 15 November 2026.
Show answer
from datetime import date
born, today = date(2004, 8, 15), date(2026, 11, 15)
age = today.year - born.year - ((today.month, today.day) < (born.month, born.day))
print(age) # 22
Exercise 2. Print today’s date as “Sunday, 15 Nov 2026”.
Show answer
from datetime import date
print(date.today().strftime("%A, %d %b %Y"))
Frequently Asked Questions
How do I get the current date and time in Python?
Use datetime.now(), or datetime.now(ZoneInfo("Asia/Dhaka")) for a time-zone-aware value. date.today() gives the date only.
How do I get a Unix timestamp?
Call .timestamp() on a datetime. To go back, use datetime.fromtimestamp(ts).
Summary
dateanddatetimerepresent calendar dates and moments.strftimeformats;strptimeparses.timedeltaadds, subtracts and measures durations.zoneinfohandles time zones; store times in UTC.
Related: Python Modules.
