Himanshu SharmaSoftware engineer
Let’s talk

Python Tutorial · Lesson 66 of 70

Python dates and times with datetime

Work with dates, times and durations using the datetime module: create them, do arithmetic with timedelta, format and parse text, and handle time zones.

14 minGoing furtherUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonCreate date and datetime values, add and subtract time with timedelta, convert to and from text with strftime and strptime, and use fixed-offset time zones.

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.

python
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)
result
2026-12-25
09:30:00
2026-11-14 15:45:30
2026 12 25
15 45 30

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

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

python
d = date(2026, 11, 14)

print(d.weekday())
print(d.strftime("%A"))
print(d.replace(day=1))
print(d.replace(year=2027))
result
5
Saturday
2026-11-01
2027-11-14

Arithmetic with timedelta

A timedelta represents a duration. Subtract two dates to get one, or add one to a date to move forward or back.

python
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)
result
2026-11-28
41 days, 0:00:00
41
2026-10-31
True

With datetime values the timedelta can also hold hours and minutes:

python
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))
result
8:30:00
8.5
2026-11-15 21:00:00

The 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
python
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"))
result
2026-11-14
14 November 2026
Saturday, 14 Nov 2026 at 15:45

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

python
parsed = datetime.strptime("14/11/2026 18:05", "%d/%m/%Y %H:%M")
print(parsed)
print(type(parsed).__name__)
print(parsed.date())
result
2026-11-14 18:05:00
datetime
2026-11-14
python
datetime.strptime("2026-11-14", "%d/%m/%Y")
result
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():

python
d = date(2026, 11, 14)
text = d.isoformat()
print(text)
print(date.fromisoformat(text) == d)
print(datetime.fromisoformat("2026-11-14T09:30:00"))
result
2026-11-14
True
2026-11-14 09:30:00

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

python
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))
result
2026-11-14 12:00:00+00:00
2026-11-14 17:30:00+05:30

Both lines describe the same instant, written for two different clocks. Naive and aware values cannot be mixed:

python
utc_time - datetime(2026, 11, 14, 12, 0)
result
TypeError: can't subtract offset-naive and offset-aware datetimes

Fixed 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 .days for short durations. Eight hours has days == 0. Use total_seconds().
  • Wrong format codes. %m is the month but %M is 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 format 2026-11-14.
  • Leaving out the leading zero in the format. strptime with %d accepts both 5 and 05, but strftime always writes 05.

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
python
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"))
result
05 December 2026
21
Saturday

Next: 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.

Check yourself

1. What is the type of date(2026, 12, 25) - date(2026, 11, 14)?
2. Which method turns a datetime into formatted text?
3. What does the format code %d stand for in strftime?
4. What happens if you subtract a naive datetime from a timezone-aware one?