Chapter 53 of 54

Date & Time in Python

Almost every real application deals with dates and times: the date an order was placed, how many days are left before an exam, when a login session expires, or what time a cricket match starts in your time zone.

Python's built-in datetime module handles all of this. In this chapter you'll learn how to create dates, format and parse them, do date arithmetic, and work safely with time zones.

The datetime Module at a Glance

The datetime module gives you a few main classes:

Class

Stores

Example

date

Year, month, day

2026-08-15

time

Hour, minute, second, microsecond

09:30:00

datetime

Date and time together

2026-08-15 09:30:00

timedelta

A duration (difference between two moments)

3 days, 4:00:00

timezone

A fixed offset from UTC

UTC+05:30

Don't get confused by the name: the module is called datetime and it contains a class called datetime. That's why you usually write from datetime import datetime.


Getting the Current Date and Time

from datetime import date, datetime

print(date.today())
print(datetime.now())

Output (depends on when you run it):

2026-11-02
2026-11-02 14:05:37.481920

The last part (.481920) is microseconds.


Creating a Specific Date or Time

from datetime import date, datetime

independence_day = date(2026, 8, 15)
match_start = datetime(2026, 8, 15, 19, 30)

print(independence_day)
print(match_start)
print(match_start.year, match_start.month, match_start.day)
print(match_start.hour, match_start.minute)
print(independence_day.weekday())     # Monday = 0 ... Sunday = 6
print(independence_day.isoweekday())  # Monday = 1 ... Sunday = 7

Output:

2026-08-15
2026-08-15 19:30:00
2026 8 15
19 30
5
6

So 15 August 2026 falls on a Saturday. Python also checks that the date is real: date(2026, 2, 30) raises a ValueError because February 2026 has only 28 days.

Date and datetime objects are immutable. To "change" one, use replace(), which returns a new object:

from datetime import date

d = date(2026, 8, 15)
next_year = d.replace(year=2027)
print(d, next_year)

Output:

2026-08-15 2027-08-15

Formatting Dates with strftime()

strftime() ("string format time") converts a date into a string in any format you want using format codes.

from datetime import datetime

dt = datetime(2026, 8, 15, 19, 30, 5)

print(dt.strftime("%d/%m/%Y"))
print(dt.strftime("%d-%b-%Y %H:%M"))
print(dt.strftime("%A, %d %B %Y"))
print(dt.strftime("%I:%M %p"))

Output:

15/08/2026
15-Aug-2026 19:30
Saturday, 15 August 2026
07:30 PM

The most useful format codes:

Code

Meaning

Example

%d

Day of month (2 digits)

15

%m

Month number (2 digits)

08

%Y / %y

Year with century / without

2026 / 26

%B / %b

Full / short month name

August / Aug

%A / %a

Full / short weekday name

Saturday / Sat

%H

Hour, 24-hour clock

19

%I and %p

Hour, 12-hour clock, and AM/PM

07, PM

%M

Minute

30

%S

Second

05

Watch out: %m is month and %M is minute. Mixing them up is the most common date-formatting bug. (Month and day names follow your system's locale; the examples above assume English.)

Dates also work directly inside f-strings: f"{dt:%d/%m/%Y}" gives 15/08/2026.


Parsing Strings with strptime()

strptime() ("string parse time") does the opposite: it reads a string and creates a datetime. The format must match the string exactly.

from datetime import datetime

text = "25/12/2026 18:45"
dt = datetime.strptime(text, "%d/%m/%Y %H:%M")
print(dt)
print(type(dt))

try:
    datetime.strptime("2026-12-25", "%d/%m/%Y")
except ValueError as e:
    print("Error:", e)

Output:

2026-12-25 18:45:00
<class 'datetime.datetime'>
Error: time data '2026-12-25' does not match format '%d/%m/%Y'

An easy way to remember: strftime = format (date to string), strptime = parse (string to date).

ISO 8601 Format

APIs and databases usually exchange dates in the standard ISO 8601 format, like 2026-12-25T18:45:00. Python has dedicated methods for it:

from datetime import datetime

dt = datetime(2026, 12, 25, 18, 45)
text = dt.isoformat()
print(text)
print(datetime.fromisoformat(text) == dt)

Output:

2026-12-25T18:45:00
True

Since Python 3.11, fromisoformat() accepts most ISO 8601 strings, including ones ending in Z for UTC.


Date Arithmetic with timedelta

A timedelta represents a duration. You can add it to or subtract it from a date, and subtracting two dates gives a timedelta.

from datetime import date, datetime, timedelta

order_date = date(2026, 11, 2)
delivery = order_date + timedelta(days=5)
print("Delivery on:", delivery)

exam = date(2027, 2, 15)
days_left = exam - order_date
print(days_left)
print("Days left:", days_left.days)

login = datetime(2026, 11, 2, 23, 30)
expires = login + timedelta(hours=2, minutes=15)
print("Session expires:", expires)
print((expires - login).total_seconds(), "seconds")

Output:

Delivery on: 2026-11-07
105 days, 0:00:00
Days left: 105
Session expires: 2026-11-03 01:45:00
8100.0 seconds

Python handles month lengths, leap years and crossing midnight for you.

Note that timedelta accepts weeks, days, hours, minutes, seconds, milliseconds and microseconds - but not months or years, because they don't have a fixed length.

Comparing Dates

Dates can be compared with the normal comparison operators and sorted like numbers.

from datetime import date

deadline = date(2026, 11, 30)
submitted = date(2026, 12, 1)

if submitted > deadline:
    print("Late by", (submitted - deadline).days, "day(s)")

dates = [date(2026, 5, 1), date(2025, 12, 31), date(2026, 1, 15)]
print(sorted(dates))

Output:

Late by 1 day(s)
[datetime.date(2025, 12, 31), datetime.date(2026, 1, 15), datetime.date(2026, 5, 1)]

Practical Example: Age Calculator

To get someone's exact age, subtract the birth year and then remove one year if their birthday hasn't come yet this year.

from datetime import date

def age_on(birth, today):
    years = today.year - birth.year
    if (today.month, today.day) < (birth.month, birth.day):
        years -= 1
    return years

birth = date(2004, 12, 10)
print(age_on(birth, date(2026, 11, 2)))
print(age_on(birth, date(2026, 12, 10)))

Output:

21
22

Comparing (month, day) tuples works because tuples compare element by element. Dividing (today - birth).days by 365 would give wrong answers around birthdays because of leap years.


Time Zones

By default, datetime objects are naive: they have no time zone information. A datetime with time zone information is called aware.

Naive datetime: just a date and clock time, no idea where in the world. Aware datetime: includes a UTC offset, so it represents one exact moment.

For a single local script, naive datetimes are fine. For servers, APIs, and users in different countries, use aware datetimes - ideally store everything in UTC and convert to local time only for display.

from datetime import datetime, timezone, timedelta

ist = timezone(timedelta(hours=5, minutes=30))

meeting = datetime(2026, 11, 2, 18, 0, tzinfo=ist)
print(meeting)
print(meeting.astimezone(timezone.utc))

Output:

2026-11-02 18:00:00+05:30
2026-11-02 12:30:00+00:00

Real Time Zones with zoneinfo

Fixed offsets don't handle daylight saving time (used in the US, UK, Europe and elsewhere). For real time zones, use the built-in zoneinfo module (Python 3.9+) with names from the IANA time zone database:

from datetime import datetime
from zoneinfo import ZoneInfo

match = datetime(2026, 11, 2, 19, 30, tzinfo=ZoneInfo("Asia/Kolkata"))

print(match.astimezone(ZoneInfo("Europe/London")))
print(match.astimezone(ZoneInfo("America/New_York")))
print(match.astimezone(ZoneInfo("Asia/Tokyo")))

Output:

2026-11-02 14:00:00+00:00
2026-11-02 09:00:00-05:00
2026-11-02 23:00:00+09:00

On 2 November 2026 the UK and the US are already back on standard time, which zoneinfo knows automatically.

Windows note: Windows does not ship the time zone database that zoneinfo needs. If you get ZoneInfoNotFoundError, install it with pip install tzdata.

Getting the Current Time in UTC

from datetime import datetime, timezone

now_utc = datetime.now(timezone.utc)   # correct, aware
print(now_utc.tzinfo)

Output:

UTC

You may see the older datetime.utcnow() in tutorials. It returns a naive datetime that is easy to misuse, and it is deprecated since Python 3.12. Use datetime.now(timezone.utc) instead.


Timestamps

A Unix timestamp is the number of seconds since 1 January 1970, 00:00 UTC. Many APIs and databases use it.

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

The separate time module also gives time.time() (the current timestamp) and time.sleep(seconds) (pause the program).


Common Mistakes

  • %m vs %M - month vs minute.

  • import datetime then calling datetime.now() - that gives AttributeError, because datetime is the module. Use datetime.datetime.now() or from datetime import datetime.

  • Mixing naive and aware datetimes - ordering them (<, >) or subtracting them raises a TypeError such as can't compare offset-naive and offset-aware datetimes, and == between them is simply always False.

  • Using timedelta(days=30) as "one month" - months have 28 to 31 days.

  • Calculating age as days // 365 - leap years make it wrong near birthdays.

  • Using datetime.utcnow() - deprecated; use datetime.now(timezone.utc).


Interview Tips

  • strftime vs strptime? strftime formats a datetime into a string; strptime parses a string into a datetime.

  • Naive vs aware? Aware datetimes carry a UTC offset/time zone and represent an exact moment; naive ones don't.

  • How should a web app store time? Store aware datetimes in UTC and convert to the user's time zone for display.

  • Practice: print all Sundays in a given month; find how many days are left until your next birthday; convert a list of IST meeting times to New York time.

Summary

  • Use date, time, datetime and timedelta from the datetime module.

  • strftime() formats dates; strptime() parses strings; isoformat()/fromisoformat() handle ISO 8601.

  • Add or subtract timedelta for date arithmetic; subtracting dates gives a timedelta.

  • Use aware datetimes with timezone.utc and zoneinfo.ZoneInfo when time zones matter.

Store time in UTC, convert to local time only when showing it to a person, and let the datetime module do the calendar maths.