Python Datetime
Dates and times appear in almost every real program: log timestamps, expiry dates, report periods, test data. The datetime module handles creating, formatting, parsing and calculating with them.
- Create date, time and datetime objects
- Format dates with strftime
- Parse text into dates with strptime
- Add, subtract and compare dates with timedelta
The main classes
| Class | Holds | Example |
|---|---|---|
date | year, month, day | date(2026, 11, 2) |
time | hour, minute, second, microsecond | time(9, 30) |
datetime | date and time together | datetime(2026, 11, 2, 9, 30) |
timedelta | a duration | timedelta(days=7) |
timezone | a fixed UTC offset | timezone.utc |
from datetime import date, time, datetime d = date(2026, 11, 2)t = time(9, 30, 15)dt = datetime(2026, 11, 2, 9, 30, 15) print(d, t, dt)print(d.year, d.month, d.day, d.weekday()) # Monday is 0print(dt.date(), dt.time())2026-11-02 09:30:15 2026-11-02 09:30:15 2026 11 2 0 2026-11-02 09:30:15
Today and now
from datetime import date, datetime today = date.today()now = datetime.now()print(type(today).__name__, type(now).__name__)print(today == now.date())date datetime True
The values depend on when you run the code, so press Try it to see your own date and time.
Format dates with strftime
strftime() turns a date into text using format codes:
| Code | Meaning | Example |
|---|---|---|
%d | day, 2 digits | 02 |
%m | month, 2 digits | 11 |
%Y | year, 4 digits | 2026 |
%B / %b | month name / short | November / Nov |
%A / %a | weekday / short | Monday / Mon |
%H:%M:%S | 24-hour time | 14:05:09 |
%I %p | 12-hour hour, AM/PM | 02 PM |
from datetime import datetime dt = datetime(2026, 11, 2, 14, 5, 9)print(dt.strftime("%d-%m-%Y"))print(dt.strftime("%A, %d %B %Y"))print(dt.strftime("%I:%M %p"))print(dt.isoformat())print(f"{dt:%Y/%m/%d %H:%M}")02-11-2026 Monday, 02 November 2026 02:05 PM 2026-11-02T14:05:09 2026/11/02 14:05
Parse text with strptime
strptime() does the reverse: it reads text in a known format and returns a datetime.
from datetime import datetime, date dt = datetime.strptime("02/11/2026 18:45", "%d/%m/%Y %H:%M")print(dt, dt.hour) print(date.fromisoformat("2026-12-25"))2026-11-02 18:45:00 18 2026-12-25
A mismatch between the text and the format raises ValueError:
from datetime import datetimedatetime.strptime("2026-11-02", "%d/%m/%Y")Traceback (most recent call last):
File "main.py", line 2, in <module>
datetime.strptime("2026-11-02", "%d/%m/%Y")
~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python3\Lib\_strptime.py", line 844, in _strptime_datetime_datetime
tt, fraction, gmtoff_fraction = _strptime(data_string, format)
~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^
File "C:\Python3\Lib\_strptime.py", line 574, in _strptime
raise ValueError("time data %r does not match format %r" %
(data_string, format))
ValueError: time data '2026-11-02' does not match format '%d/%m/%Y'Date arithmetic with timedelta
from datetime import date, timedelta start = date(2026, 11, 2)print(start + timedelta(days=30))print(start - timedelta(weeks=2)) deadline = date(2026, 12, 31)remaining = deadline - start # subtracting dates gives a timedeltaprint(remaining, remaining.days)2026-12-02 2026-10-19 59 days, 0:00:00 59
from datetime import datetime, timedelta login = datetime(2026, 11, 2, 9, 15)logout = datetime(2026, 11, 2, 17, 40)worked = logout - loginprint(worked)print(worked.total_seconds() / 3600, "hours")8:25:00 8.416666666666666 hours
Compare and sort dates
from datetime import date dates = [date(2026, 3, 1), date(2025, 12, 25), date(2026, 1, 15)]print(sorted(dates))print(max(dates), date(2026, 1, 1) < date(2026, 1, 2))[datetime.date(2025, 12, 25), datetime.date(2026, 1, 15), datetime.date(2026, 3, 1)] 2026-03-01 True
Age and days until a birthday
from datetime import date def age_on(birth, on_day): years = on_day.year - birth.year if (on_day.month, on_day.day) < (birth.month, birth.day): years -= 1 # birthday not reached yet this year return years print(age_on(date(1995, 12, 20), date(2026, 11, 2)))print(age_on(date(1995, 6, 1), date(2026, 11, 2)))30 31
Time zones
A datetime without time zone information is “naive”. Attach a zone to make it “aware”. zoneinfo (Python 3.9+) uses the IANA time zone names.
from datetime import datetime, timezone, timedelta utc_time = datetime(2026, 11, 2, 12, 0, tzinfo=timezone.utc)ist = timezone(timedelta(hours=5, minutes=30))print(utc_time.astimezone(ist))print(utc_time.astimezone(ist).strftime("%H:%M %z"))2026-11-02 17:30:00+05:30 17:30 +0530
Store and compare times in UTC, and convert to the user’s local zone only when displaying them.
Timestamps
from datetime import datetime, timezone dt = datetime(2026, 1, 1, tzinfo=timezone.utc)ts = dt.timestamp()print(ts)print(datetime.fromtimestamp(ts, tz=timezone.utc))1767225600.0 2026-01-01 00:00:00+00:00
Check your understanding
Predict the output
from datetime import date, timedeltad = date(2024, 2, 28) + timedelta(days=2)print(d, d.strftime("%a"))2024-03-01 Fri
2024 is a leap year, so the day after 28 February is the 29th, and two days later is 1 March, a Friday.
Quick quiz
1. Which method turns a datetime into formatted text?
f for format. strptime (p for parse) goes the other way.
2. What is the type of date(2026, 12, 31) - date(2026, 11, 2)?
Subtracting two dates gives a duration.
3. What does %B produce?
%b gives the short name.
Exercise: days until a deadline
Given today’s date and a deadline, print how many days are left and the deadline’s weekday name. Use fixed dates so the output is repeatable.
today = 2026-11-02, deadline = 2027-01-15
74 days left Deadline is on a Friday
Hint 1
Subtract the dates and use .days.
from datetime import date today = date(2026, 11, 2)deadline = date.fromisoformat("2027-01-15") left = (deadline - today).daysprint(f"{left} days left")print("Deadline is on a", deadline.strftime("%A"))74 days left Deadline is on a Friday
Subtracting two date objects returns a timedelta, and .days gives the whole number of days. %A prints the full weekday name.
Program Practice
20 Python Datetime Programs
Every program has a step-by-step explanation, colour-coded code and its real output.
Python datetime FAQ
How do I get the current date and time in Python?
from datetime import datetime then datetime.now(). Use date.today() for the date only.
How do I convert a string to a date in Python?
Use datetime.strptime(text, format), for example datetime.strptime("02/11/2026", "%d/%m/%Y"), or date.fromisoformat("2026-11-02") for ISO text.
How do I add days to a date in Python?
Add a timedelta: date + timedelta(days=10).
What is the difference between strftime and strptime?
strftime formats a date as text; strptime parses text into a date.
1 thought on “Python Datetime”