After this lesson you will be able to store a date or time in a variable, work out how many days lie between two dates, add a week to a deadline, and convert dates to and from text. Dates look easy, but they have many awkward details such as month lengths and leap years, so use the standard library rather than doing the arithmetic yourself.
Dates, times and datetimes
The datetime module has four main types. A date holds a year, month and day. A time holds hours, minutes and seconds. A datetime holds both. A timedelta is a length of time.
from datetime import date, time, datetime, timedelta
due = date(2026, 12, 25)
opens = time(9, 30)
meeting = datetime(2026, 11, 14, 15, 45, 30)
print(due)
print(opens)
print(meeting)
print(due.year, due.month, due.day)
print(meeting.hour, meeting.minute, meeting.second)2026-12-25
09:30:00
2026-11-14 15:45:30
2026 12 25
15 45 30To get the current moment you would call date.today() or datetime.now(). Their results change every time you run them, so the examples here use fixed dates instead, and the lines that depend on today's date are marked as not run.
from datetime import date, datetime
print(date.today())
print(datetime.now())Weekdays and replacing parts
weekday() gives Monday as 0 up to Sunday as 6, and strftime("%A") gives the day's name. replace returns a copy with some parts changed.
d = date(2026, 11, 14)
print(d.weekday())
print(d.strftime("%A"))
print(d.replace(day=1))
print(d.replace(year=2027))5
Saturday
2026-11-01
2027-11-14Arithmetic with timedelta
A timedelta represents a duration. Subtract two dates to get one, or add one to a date to move forward or back.
borrowed = date(2026, 11, 14)
due_back = borrowed + timedelta(days=14)
print(due_back)
gap = date(2026, 12, 25) - borrowed
print(gap)
print(gap.days)
print(borrowed - timedelta(weeks=2))
print(due_back > borrowed)2026-11-28
41 days, 0:00:00
41
2026-10-31
TrueWith datetime values the timedelta can also hold hours and minutes:
start = datetime(2026, 11, 14, 9, 0)
end = datetime(2026, 11, 14, 17, 30)
worked = end - start
print(worked)
print(worked.total_seconds() / 3600)
print(start + timedelta(hours=36))8:30:00
8.5
2026-11-15 21:00:00The days attribute of a timedelta is only the whole-day part. Use total_seconds() when you need the full length.
Formatting dates as text with strftime
strftime ("string from time") builds text using format codes that start with a percent sign.
| Code | Meaning | Example |
|---|---|---|
%Y |
four-digit year | 2026 |
%m |
month, two digits | 11 |
%d |
day, two digits | 14 |
%B |
month name | November |
%b |
short month name | Nov |
%A |
weekday name | Saturday |
%H:%M:%S |
hours, minutes, seconds (24-hour) | 15:45:30 |
meeting = datetime(2026, 11, 14, 15, 45, 30)
print(meeting.strftime("%Y-%m-%d"))
print(meeting.strftime("%d %B %Y"))
print(meeting.strftime("%A, %d %b %Y at %H:%M"))2026-11-14
14 November 2026
Saturday, 14 Nov 2026 at 15:45Month and weekday names follow the language settings of the computer, so they may appear in a different language elsewhere.
Parsing text with strptime
strptime ("string parse time") goes the other way. You give it the text and a format describing it, and it returns a datetime.
parsed = datetime.strptime("14/11/2026 18:05", "%d/%m/%Y %H:%M")
print(parsed)
print(type(parsed).__name__)
print(parsed.date())2026-11-14 18:05:00
datetime
2026-11-14datetime.strptime("2026-11-14", "%d/%m/%Y")ValueError: time data '2026-11-14' does not match format '%d/%m/%Y'If the text does not match the format, you get a ValueError, so wrap parsing of user input in try.
The ISO format
The international standard writes dates as YYYY-MM-DD. It sorts correctly even as plain text, so it is the best format for storing dates. Use isoformat() and fromisoformat():
d = date(2026, 11, 14)
text = d.isoformat()
print(text)
print(date.fromisoformat(text) == d)
print(datetime.fromisoformat("2026-11-14T09:30:00"))2026-11-14
True
2026-11-14 09:30:00Time zones
A datetime created as above is naive: it has no time zone, so it could mean any place on Earth. An aware datetime carries an offset from UTC. The simplest tool is timezone with a fixed offset.
from datetime import timezone
utc_time = datetime(2026, 11, 14, 12, 0, tzinfo=timezone.utc)
ist = timezone(timedelta(hours=5, minutes=30))
print(utc_time)
print(utc_time.astimezone(ist))2026-11-14 12:00:00+00:00
2026-11-14 17:30:00+05:30Both lines describe the same instant, written for two different clocks. Naive and aware values cannot be mixed:
utc_time - datetime(2026, 11, 14, 12, 0)TypeError: can't subtract offset-naive and offset-aware datetimesFixed offsets cannot know about daylight saving changes. For named zones such as a city, Python 3.9 added the zoneinfo module, which depends on time zone data being available on the computer, so it is not shown here. A good rule is to store times in UTC and convert to a local zone only when displaying them.
Common mistakes
- Subtracting dates and expecting a number. The result is a
timedelta. Use its.days. - Using
.daysfor short durations. Eight hours hasdays == 0. Usetotal_seconds(). - Wrong format codes.
%mis the month but%Mis the minute. Mixing them up gives silently wrong values. - Mixing naive and aware datetimes. Python raises a
TypeError. Decide on one style. - Storing dates as free text. Strings such as
"14/11/26"are ambiguous. Prefer the ISO format2026-11-14. - Leaving out the leading zero in the format.
strptimewith%daccepts both5and05, butstrftimealways writes05.
Exercise
A library lends books for 21 days. For a book borrowed on 2026-11-14, print its due date in the form 05 December 2026, then print how many days remain between the borrow date and the due date. Finally, print the due date's weekday name.
Show one possible answer
from datetime import date, timedelta
borrowed = date(2026, 11, 14)
due = borrowed + timedelta(days=21)
print(due.strftime("%d %B %Y"))
print((due - borrowed).days)
print(due.strftime("%A"))05 December 2026
21
SaturdayNext: type hints show how to describe what kind of values your functions expect. A video version of this topic is in the video course at /learn/python/.
Key points
- The datetime module provides date, time, datetime and timedelta. Import them with from datetime import ...
- Subtracting two dates gives a timedelta, and adding a timedelta to a date gives a new date.
- strftime turns a date into text using format codes such as %Y-%m-%d, and strptime parses text into a datetime.
- isoformat() and fromisoformat() convert to and from the standard YYYY-MM-DD form.
- A datetime is naive unless it has a time zone. Mixing naive and aware values raises an error.