Skip to main content
eLearner.app
Module 8 · Lesson 2 of 430/36 in the course~12 min
Module lessons (2/4)

datetime: dates and times

The datetime module provides the classes to represent dates and times.

The three main classes

  • date — date only (year, month, day)
  • time — time only (hour, minute, second, microsecond)
  • datetime — date + time together
  • timedelta — a duration (difference between two instants)
Python
from datetime import date, time, datetime, timedelta

date(2025, 1, 1)                  # datetime.date(2025, 1, 1)
time(14, 30, 0)                   # datetime.time(14, 30)
datetime(2025, 1, 1, 14, 30, 0)   # datetime.datetime(2025, 1, 1, 14, 30)

"Now": now and today

Python
datetime.now()        # current date + time
date.today()          # current date only

Arithmetic with timedelta

Python
from datetime import datetime, timedelta

ora = datetime(2025, 1, 1, 12, 0)
domani = ora + timedelta(days=1)
una_ora_fa = ora - timedelta(hours=1)

# difference between two datetimes -> timedelta
delta = domani - ora
delta.days        # 1
delta.total_seconds()   # 86400.0

timedelta accepts days, seconds, microseconds, milliseconds, minutes, hours, weeks (NOT months or years, which are ambiguous).

Formatting: strftime

Transforms datetime → string according to a pattern.

Python
ora = datetime(2025, 1, 1, 14, 30)
ora.strftime("%Y-%m-%d")         # '2025-01-01'
ora.strftime("%d/%m/%Y %H:%M")   # '01/01/2025 14:30'
ora.strftime("%A %d %B %Y")      # 'Wednesday 01 January 2025' (locale-dependent)

Most used directives: %Y 4-digit year, %m 2-digit month, %d 2-digit day, %H 24h hour, %M minutes, %S seconds.

Parsing: strptime

The opposite: string → datetime, given the expected pattern.

Python
datetime.strptime("01/01/2025", "%d/%m/%Y")
# datetime.datetime(2025, 1, 1, 0, 0)

ISO 8601

For data exchange always prefer the ISO 8601 format (YYYY-MM-DDTHH:MM:SS):

Python
ora.isoformat()                 # '2025-01-01T14:30:00'
datetime.fromisoformat("2025-01-01T14:30:00")

Timezones and aware datetimes

By default, datetime objects in Python are naive (meaning they contain no timezone info). For real-world applications, it is best practice to make them aware by setting timezone info via datetime.timezone.utc or utilizing the zoneinfo module.

Try it

Exercise#python.m8.l2.e1
Attempts: 0Loading…

Compute the date 30 days after January 1, 2025 and format it as 'YYYY-MM-DD' in the variable `date_str`. Evaluate `date_str`.

Loading editor…
Show hint

base + timedelta(days=30), then .strftime

Solution available after 3 attempts

Review exercise

Exercise#python.m8.l2.e2
Attempts: 0Loading…

Given the string `s = '15/03/2025'`, parse it with strptime into the variable `d` (datetime object). Evaluate the integer day of the week `d.weekday()` (0=Mon, 6=Sun).

Loading editor…
Show hint

strptime with the Italian-format pattern.

Solution available after 3 attempts

Additional challenge

Exercise#python.m8.l2.e3
Attempts: 0Loading…

Import `date` from the `datetime` module. Calculate the difference in days between December 25, 2026 (`date(2026, 12, 25)`) and December 20, 2026 (`date(2026, 12, 20)`). Store the integer number of days (using the `.days` attribute of the delta) in `days_diff`. Finally, evaluate the variable.

Loading editor…
Show hint

The difference between two dates returns a timedelta. Access the integer days with delta.days.

Solution available after 3 attempts