Python Tutorial › Modules › Datetime

Python Datetime

IntermediateLesson 36 of 4712 min read11 runnable examples

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.

Advertisement
In this lesson
  • 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

ClassHoldsExample
dateyear, month, daydate(2026, 11, 2)
timehour, minute, second, microsecondtime(9, 30)
datetimedate and time togetherdatetime(2026, 11, 2, 9, 30)
timedeltaa durationtimedelta(days=7)
timezonea fixed UTC offsettimezone.utc
Python
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())
Output
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

Python
from datetime import date, datetime today = date.today()now = datetime.now()print(type(today).__name__, type(now).__name__)print(today == now.date())
Output
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:

CodeMeaningExample
%dday, 2 digits02
%mmonth, 2 digits11
%Yyear, 4 digits2026
%B / %bmonth name / shortNovember / Nov
%A / %aweekday / shortMonday / Mon
%H:%M:%S24-hour time14:05:09
%I %p12-hour hour, AM/PM02 PM
Python
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}")
Output
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.

Python
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"))
Output
2026-11-02 18:45:00 18
2026-12-25

A mismatch between the text and the format raises ValueError:

Python
from datetime import datetimedatetime.strptime("2026-11-02", "%d/%m/%Y")
Output
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

Python
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)
Output
2026-12-02
2026-10-19
59 days, 0:00:00 59
Python
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")
Output
8:25:00
8.416666666666666 hours

Compare and sort dates

Python
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))
Output
[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

Python
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)))
Output
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.

Python
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"))
Output
2026-11-02 17:30:00+05:30
17:30 +0530
Tip

Store and compare times in UTC, and convert to the user’s local zone only when displaying them.

Timestamps

Python
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))
Output
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"))

Quick quiz

1. Which method turns a datetime into formatted text?

2. What is the type of date(2026, 12, 31) - date(2026, 11, 2)?

3. What does %B produce?

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.

Input
today = 2026-11-02, deadline = 2027-01-15
Expected output
74 days left
Deadline is on a Friday
Hint 1

Subtract the dates and use .days.

Program Practice

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”

Leave a Comment