Dates & Times (datetime)
Published by Brayan K
Almost every real program deals with time: when an order was placed, how old an account is, what to schedule next. Python's datetime module gives you proper date objects you can compare, format, and do arithmetic with — far safer than juggling strings.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
The datetime module, and the datetime type inside it
The module is called datetime, and so is the most used type inside it, which is a common source of errors. After import datetime, the name datetime is the module, so the types are datetime.date and datetime.datetime:
import datetime
print(datetime.date(2024, 3, 1))
print(datetime.now())
# ✅ Expected output:
# 2024-03-01
# ✅ Expected error:
# AttributeError: module 'datetime' has no attribute 'now'Most code imports the types themselves with from datetime import ..., which Modules and Packages explains. Then datetime is the type. This lesson uses four of the module's types (the other two are timezone, which the FAQ below uses, and tzinfo, the base class time zones are built on):
- date: a calendar date, year, month and day;
- time: a time of day;
- datetime: a date and a time together;
- timedelta: a length of time, such as three days or two hours.
from datetime import date, datetime, timedelta
print(date(2024, 3, 1))
print(datetime(2024, 3, 1, 9, 30))
print(timedelta(days=1, hours=2))
# ✅ Expected output:
# 2024-03-01
# 2024-03-01 09:30:00
# 1 day, 2:00:00date.today() and datetime.now() read the clock, so they give a different answer every time, and in this site's editor they use your browser's time zone. The examples here use fixed dates, so their output never changes.
Text is not a date
Dates kept as text compare character by character:
print("09/01/2024" < "10/12/2023")
print("2024-01-09" < "2024-01-10")
# ✅ Expected output:
# True
# TrueThe first line says 9 January 2024 comes before 10 December 2023, because "0" comes before "1". Text in the year-month-day layout, with zeros in front, does sort in date order, which is why that layout is the usual way to store a date as text. But arithmetic needs a real date, and a date doesn't add a plain number either:
from datetime import date
due = date(2024, 3, 1)
print(due + 30)
# ✅ Expected error:
# TypeError: unsupported operand type(s) for +: 'datetime.date' and 'int'Thirty what? Say it with a timedelta:
from datetime import date, timedelta
due = date(2024, 3, 1)
print(due + timedelta(days=30))
print(date(2024, 1, 9) < date(2023, 12, 10))
print(due.year, due.month, due.day)
# ✅ Expected output:
# 2024-03-31
# False
# 2024 3 1year, month and day are values stored on the date, read without brackets: due.year() stops with a TypeError, because the year is a number, not a method.
Turning a date into text: strftime() and f-strings
strftime() (f for format) turns a date into text, following codes that start with %. The same codes work after the colon in an f-string, the date codes that f-strings & String Formatting mentioned:
from datetime import datetime
d = datetime(2024, 1, 15, 14, 32, 8)
print(d)
print(d.strftime("%Y-%m-%d"))
print(d.strftime("%d/%m/%Y"))
print(d.strftime("%A, %B %d, %Y"))
print(d.strftime("%I:%M %p"))
print(f"{d:%d %b %Y}")
print(f"Due on {d:%A}")
# ✅ Expected output:
# 2024-01-15 14:32:08
# 2024-01-15
# 15/01/2024
# Monday, January 15, 2024
# 02:32 PM
# 15 Jan 2024
# Due on Monday| Code | Meaning | For the date above |
|---|---|---|
| %Y | year, four digits | 2024 |
| %m | month number, two digits | 01 |
| %B %b | month name, full or short | January Jan |
| %d | day of the month, two digits | 15 |
| %A %a | weekday name, full or short | Monday Mon |
| %H %I | hour on a 24-hour or 12-hour clock | 14 02 |
| %M %S | minute and second | 32 08 |
| %p | AM or PM | PM |
The codes are case-sensitive: %m is the month and %M the minute. Month and weekday names come out in English unless a program switches the language with the locale module.
Reading text into a date: strptime() needs the exact layout
datetime.strptime() (p for parse) does the reverse. You give it the text and a format that describes it exactly, separators included. A format that doesn't fit stops the program:
from datetime import datetime
print(datetime.strptime("01/03/2024", "%d/%m/%Y"))
print(datetime.strptime("01/03/2024", "%Y-%m-%d"))
# ✅ Expected output:
# 2024-03-01 00:00:00
# ✅ Expected error:
# ValueError: time data '01/03/2024' does not match format '%Y-%m-%d'Text with more in it than the format describes, such as a time after the date, stops with a ValueError that quotes the leftover part. Worse is a wrong code that still fits, which gives a wrong date with no error at all:
from datetime import date, datetime
print(datetime.strptime("2024-03-01", "%Y-%M-%d"))
print(datetime.strptime("2024-03-01", "%Y-%m-%d"))
pushed = datetime.strptime("2024-05-10T08:00:00Z", "%Y-%m-%dT%H:%M:%SZ")
print(pushed)
print(pushed.isoformat())
print(date.fromisoformat("2024-03-01"))
# ✅ Expected output:
# 2024-01-01 00:03:00
# 2024-03-01 00:00:00
# 2024-05-10 08:00:00
# 2024-05-10T08:00:00
# 2024-03-01With %M, the 03 became three minutes past midnight on 1 January. Letters that aren't codes, such as the T and the Z in timestamps from web services, match themselves, which Checkpoint: A Real-World Script relies on. isoformat() and fromisoformat() write and read the standard year-month-day layout without a format at all. From Python 3.11, datetime.fromisoformat() also reads a timestamp with a final Z, such as 2024-05-10T08:00:00Z; 3.10 doesn't, and date.fromisoformat() never accepts a Z.
Lengths of time: timedelta
A timedelta is a length of time. Adding one to a date moves it; subtracting two dates gives one. Its .seconds is only the part left over after the whole days, not the whole length:
from datetime import timedelta
gap = timedelta(days=1, hours=2)
print(gap)
print(gap.days)
print(gap.seconds)
print(gap.total_seconds())
print(timedelta(weeks=2))
# ✅ Expected output:
# 1 day, 2:00:00
# 1
# 7200
# 93600.0
# 14 days, 0:00:00Subtracting a later moment from an earlier one gives a negative length, which Python stores as a negative number of days plus a positive number of hours:
from datetime import datetime
due = datetime(2024, 1, 17)
returned = datetime(2024, 1, 20, 9, 0)
late = due - returned
print(late)
print(late.days)
print((returned.date() - due.date()).days)
# ✅ Expected output:
# -4 days, 15:00:00
# -4
# 3Minus 4 days plus 15 hours is minus 3 days and 9 hours, so .days says -4. Subtract in the order that gives a positive answer, and use .date() to drop the time when only the day counts.
Python checks the calendar
A date has to exist. timedelta knows how long each month is, leap years included:
from datetime import date, timedelta
print(date(2024, 2, 28) + timedelta(days=1))
print(date(2023, 2, 28) + timedelta(days=1))
# ✅ Expected output:
# 2024-02-29
# 2023-03-01And date() refuses a day that isn't there: date(2023, 2, 29) stops with ValueError: day is out of range for month. Python 3.14 says exactly what is wrong: day 29 must be in range 1..28 for month 2 in year 2023.
A pattern from Regular Expressions (re) can check that text looks like a date, but only strptime() or date() knows that 2024-02-30 isn't one. The calendar is also why timedelta has no months=: months differ in length. Changing the month with replace() works while the day fits:
from datetime import date
print(date(2024, 1, 15).replace(month=2))
# ✅ Expected output:
# 2024-02-15The 31st has no February twin, so date(2024, 1, 31).replace(month=2) stops with the same ValueError, worded on 3.14 as day 31 must be in range 1..29 for month 2 in year 2024. replace() makes a new date, because a date can't be changed: assigning to d.year stops with an AttributeError. To move by months, decide what a month later means for your program, such as 30 days, or the same day clipped to the end of a shorter month.
A date and a datetime don't mix
Arithmetic between a date and a datetime fails, because one has a time and the other doesn't. .date() turns a datetime into a date first:
from datetime import date, datetime
booked = datetime(2024, 3, 1, 9, 30)
print(booked.date() - date(2024, 2, 1))
print(booked - date(2024, 2, 1))
# ✅ Expected output:
# 29 days, 0:00:00
# ✅ Expected error:
# TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'datetime.date'The same goes for a datetime that carries a time zone and one that doesn't: subtracting them stops with a TypeError. Time Zones with zoneinfo covers time zones; named zones such as Europe/London need a zone database, which this site's in-browser editor doesn't have.
A worked example: a library loan slip
Text in, real dates for the arithmetic, text out: read the borrowing date, add the loan period, compare with a fixed "today", and print the slip.
from datetime import datetime, timedelta
LOAN_DAYS = 14
# 1. Read the text into a datetime: day, slash, month, slash, 4-digit year.
borrowed = datetime.strptime("03/01/2024", "%d/%m/%Y")
print(borrowed)
# 2. Add the loan period.
due = borrowed + timedelta(days=LOAN_DAYS)
print(due.strftime("%d/%m/%Y"))
# 3. Compare with a fixed "today", so the output never changes.
today = datetime(2024, 1, 20)
gap = due - today
print(gap.days)
# 4. Turn the gap into words. A negative gap means the due date has passed.
if gap.days < 0:
status = f"OVERDUE by {-gap.days} days"
else:
status = f"due in {gap.days} days"
print("Borrowed:", borrowed.strftime("%A %d %B %Y"))
print("Due back:", due.strftime("%A %d %B %Y"))
print("Status: ", status)
# ✅ Expected output:
# 2024-01-03 00:00:00
# 17/01/2024
# -3
# Borrowed: Wednesday 03 January 2024
# Due back: Wednesday 17 January 2024
# Status: OVERDUE by 3 daysPractice: a membership renewal date
A membership that started on 1 March 2024 lasts 30 days. Fill the three blanks with the values in the hint lines, in order: the layout of the stored text, the number of days, and the codes for the weekday, day, month name and year.
from datetime import datetime, timedelta
joined = datetime.strptime("2024-03-01", "___")
renews = joined + timedelta(days=___)
print(f"Renews: {renews:___}")
today = datetime(2024, 3, 20)
print("Days to go:", (renews - today).days)
# 👉 replace ___ with %Y-%m-%d
# 👉 replace ___ with 30
# 👉 replace ___ with %A %d %B %Y
# ✅ Expected output:
# Renews: Sunday 31 March 2024
# Days to go: 11On your own: a sprint schedule
A team works in two-week sprints, starting on Monday 5 February 2024. A sprint ends 13 days after it starts. Print the start and end of the first four sprints, as in Sprint 1: 05 Feb to 18 Feb. Sprint 2 crosses the end of February in a leap year. Then compare with this solution:
from datetime import date, timedelta
project_start = date(2024, 2, 5)
for n in range(1, 5):
start = project_start + timedelta(weeks=2 * (n - 1))
end = start + timedelta(days=13)
print(f"Sprint {n}: {start:%d %b} to {end:%d %b}")
# ✅ Expected output:
# Sprint 1: 05 Feb to 18 Feb
# Sprint 2: 19 Feb to 03 Mar
# Sprint 3: 04 Mar to 17 Mar
# Sprint 4: 18 Mar to 31 MarSprint 2 ends on 3 March. Without 29 February it would have ended on 4 March, and timedelta counted that for you.
Practice quiz
What does print(date(2024, 1, 31) + timedelta(days=1)) print?
- 2024-01-32
- 2024-02-01
- An error
- 2024-02-01 00:00:00
Answer: 2024-02-01. timedelta moves across the end of the month, and a date prints without a time.
What does print(timedelta(days=1, hours=2).seconds) print?
- 7200
- 93600
- 2
- 26
Answer: 7200. .seconds is only the part after the whole days. total_seconds() gives 93600.0.
What does datetime.strptime("2024-03-01", "%Y-%M-%d") give?
- 2024-03-01 00:00:00
- An error
- 2024-01-01 00:03:00
- 2024-03-01 03:00:00
Answer: 2024-01-01 00:03:00. %M is minutes. The 03 becomes three minutes past midnight on 1 January, with no error.
import datetime, then datetime.now(). What happens?
- It prints the current date and time
- It stops with AttributeError: module 'datetime' has no attribute 'now'
- It prints None
- It stops with a NameError
Answer: It stops with AttributeError: module 'datetime' has no attribute 'now'. datetime here is the module. The type with now() is datetime.datetime.
What does print("09/01/2024" < "10/12/2023") print?
- False
- An error
- None
- True
Answer: True. Text compares character by character, so "0" before "1" decides it, whatever the dates are.
What does date(2023, 2, 29) do?
- It gives 2023-02-28
- It gives 2023-03-01
- It stops with a ValueError
- It gives 2023-02-29
Answer: It stops with a ValueError. 2023 wasn't a leap year, and date() checks the calendar.
late = datetime(2024, 1, 17) - datetime(2024, 1, 20, 9, 0). What is late.days?
- -4
- -3
- 3
- 4
Answer: -4. A negative gap is stored as -4 days plus 15 hours, so .days is -4.
What does f"{date(2024, 7, 4):%B}" give?
- 07
- Jul
- Thursday
- July
Answer: July. %B is the full month name; %b would give Jul.
Continue this course
- Previous: Regular Expressions (re)
- Next: Working with JSON — Parse and create JSON with json.loads and json.dumps
- Quick reference: Python cheat sheet › Standard Library
Frequently asked questions
Why does datetime.utcnow() print a warning?
On Python 3.12 and later, utcnow() prints a DeprecationWarning, because the datetime it returns doesn't say it's in UTC. datetime.now(timezone.utc) gives the same moment with the time zone attached, and works on every version.
Why does now() show a different time in the online editor?
datetime.now() and date.today() read the clock and time zone of whatever runs the code. In this site's editor that's your own browser, so the answer depends on where you are and when you run it, which is why this lesson's examples use fixed dates.
How do I store a date in JSON or a file?
As text in the standard layout: d.isoformat() gives text such as 2024-03-01, and date.fromisoformat() reads it back. That text also sorts in date order. Working with JSON shows how to write it out.