Skip to content
Laviyx Learn

Try

Python course menu

Python Date and Time: datetime, timedelta, strftime and Time Zones

Learn Python's datetime module: create dates and times, get today's date, format with strftime, parse strings with strptime, add days with timedelta, calculate differences and ages, and handle time zones.

Intermediate7 min readUpdated
On this page

Dates and times appear in almost every real program: order dates, deadlines, birthdays, log timestamps. Python's built-in datetime module represents them as proper objects you can compare, format, and do arithmetic with.

The main types#

TypeHoldsExample
datea calendar date2026-10-23
datetimea date and a time2026-10-23 14:30:05
timea time of day14:30:05
timedeltaa duration30 days
Python
from datetime import date, datetime, timedelta

Creating dates and times#

Python
d = date(2026, 10, 23)
print(d, d.year, d.month, d.day)
print(d.weekday(), d.isoweekday())
Output
2026-10-23 2026 10 23
4 5

weekday() counts Monday as 0; isoweekday() counts Monday as 1. Invalid dates are rejected:

Python
date(2026, 2, 30)
Output
ValueError: day is out of range for month
Python
moment = datetime(2026, 10, 23, 14, 30, 5)
print(moment)
print(moment.date(), moment.time())
Output
2026-10-23 14:30:05
2026-10-23 14:30:05

For the current date and time, use date.today() and datetime.now(). (Their output changes every time you run them, which is why these examples use fixed dates.)

Formatting with strftime#

strftime ("string format time") turns a date into text using format codes:

Python
print(d.strftime("%A, %d %B %Y"))
print(moment.strftime("%d/%m/%Y %I:%M %p"))
Output
Friday, 23 October 2026
23/10/2026 02:30 PM
CodeMeaningExample
%Y / %yyear2026 / 26
%mmonth number10
%B / %bmonth name / shortOctober / Oct
%dday of month23
%A / %aweekday / shortFriday / Fri
%Hhour (24-hour)14
%I / %phour (12-hour) / AM-PM02 / PM
%M / %Sminute / second30 / 05

Parsing text with strptime#

strptime ("string parse time") does the reverse, reading text in a known format:

Python
parsed = datetime.strptime("23-10-2026 09:15", "%d-%m-%Y %H:%M")
print(parsed, type(parsed).__name__)

print(datetime.fromisoformat("2026-10-23T09:15:00"))
Output
2026-10-23 09:15:00 datetime
2026-10-23 09:15:00

fromisoformat() is the quickest way to read ISO-formatted strings, which is what most APIs and databases produce.

Date arithmetic with timedelta#

Add or subtract a timedelta to move through time:

Python
d = date(2026, 10, 23)
print(d + timedelta(days=30))
print(d - timedelta(weeks=1))
Output
2026-11-22
2026-10-16

Subtracting two dates gives a timedelta:

Python
start = date(2026, 1, 1)
end = date(2026, 10, 23)
gap = end - start
print(gap, gap.days, type(gap).__name__)
Output
295 days, 0:00:00 295 timedelta

Dates also compare naturally:

Python
d1 = date(2026, 10, 23)
d2 = date(2026, 12, 25)
print(d1 < d2, (d2 - d1).days)
Output
True 63

Calculating age#

Subtract the years, then subtract one more if this year's birthday has not happened yet:

Python
birthday = date(2005, 3, 15)
today = date(2026, 10, 23)

age = today.year - birthday.year - ((today.month, today.day) < (birthday.month, birthday.day))
print(age)
Output
21

The comparison of (month, day) tuples is True (counted as 1) when the birthday is still to come.

Time zones#

A datetime without time zone information is naive. For anything involving users in different places, store times in UTC and convert for display:

Python
from datetime import datetime, timezone
from zoneinfo import ZoneInfo

utc_time = datetime(2026, 10, 23, 9, 0, tzinfo=timezone.utc)
print(utc_time.astimezone(ZoneInfo("Asia/Kolkata")))
Output
2026-10-23 14:30:00+05:30

zoneinfo (Python 3.9+) knows the world's time zones and their daylight-saving rules. On Windows you may need to pip install tzdata for it to find the time zone database.

Common mistakes#

Practice#

Practice exercise

A loan starts on 23 October 2026 with a payment due every 30 days. Print the first four due dates (counting the start date as payment 1) in the format 23 Oct 2026.

Show hint

Loop for i in range(4) and add timedelta(days=30 * i). Format with "%d %b %Y".

Show solution
Python
from datetime import date, timedelta

start = date(2026, 10, 23)
for i in range(4):
    due = start + timedelta(days=30 * i)
    print(i + 1, due.strftime("%d %b %Y"))
Output
1 23 Oct 2026
2 22 Nov 2026
3 22 Dec 2026
4 21 Jan 2027

Because months have 30 or 31 days, "every 30 days" slowly drifts earlier in the month.

Key takeaway#

Finished this lesson?