Kahibaro
Discord Login Register

12.3.3 datetime

Working with `datetime`

The datetime module in Python’s standard library helps you work with dates, times, and time intervals. It is useful any time you need to record “when” something happens, calculate durations, or format dates and times nicely.

You typically start with:

import datetime

or, for convenience:

from datetime import date, time, datetime, timedelta

In this chapter, we’ll focus on the most commonly used parts: date, time, datetime, timedelta, and basic formatting/parsing.


Dates with `date`

A date represents a calendar date (year, month, day) without any time of day.

Creating dates

from datetime import date
# Today's date
today = date.today()
print(today)             # e.g. 2025-03-15
# A specific date: year, month, day
birthday = date(2000, 5, 20)
print(birthday)          # 2000-05-20

You can access parts of the date:

print(today.year)        # e.g. 2025
print(today.month)       # 3
print(today.day)         # 15

Comparing dates

You can compare date objects with comparison operators:

if today > birthday:
    print("Today is after your birthday.")

This works because date objects know how to compare themselves.


Times with `time`

A time represents a time of day (hours, minutes, seconds, microseconds) without any date.

Creating times

from datetime import time
# hour, minute, second
start = time(9, 30, 0)
print(start)             # 09:30:00
# Only hour and minute
evening = time(18, 45)
print(evening)           # 18:45:00

You can access components:

print(start.hour)        # 9
print(start.minute)      # 30
print(start.second)      # 0

Date and time together: `datetime`

A datetime combines both date and time in one object.

Getting the current date and time

from datetime import datetime
now = datetime.now()
print(now)               # e.g. 2025-03-15 14:27:53.123456

datetime.now() gives the current local date and time.

You can also get just the current date or time from a datetime:

print(now.date())        # e.g. 2025-03-15
print(now.time())        # e.g. 14:27:53.123456

Creating a specific `datetime`

meeting = datetime(2025, 4, 1, 10, 30, 0)
print(meeting)           # 2025-04-01 10:30:00
print(meeting.year)      # 2025
print(meeting.month)     # 4
print(meeting.day)       # 1
print(meeting.hour)      # 10
print(meeting.minute)    # 30

Comparing `datetime` values

You can compare datetime objects just like date:

deadline = datetime(2025, 4, 1, 23, 59)
if now > deadline:
    print("Deadline has passed.")
else:
    print("You still have time!")

Time differences with `timedelta`

timedelta represents a duration (a difference between two moments in time). You can:

Subtracting dates and datetimes

from datetime import date, datetime, timedelta
today = date.today()
future = date(2025, 12, 31)
difference = future - today
print(difference)        # e.g. 291 days, 0:00:00
print(difference.days)   # e.g. 291

With datetime:

now = datetime.now()
event = datetime(2025, 6, 1, 12, 0)
time_left = event - now
print(time_left)         # e.g. 78 days, 21:15:03.123456
print(time_left.days)    # whole days
print(time_left.seconds) # remaining seconds after days

Creating and using `timedelta`

You can create durations:

one_day = timedelta(days=1)
two_hours = timedelta(hours=2)
mix = timedelta(days=2, hours=3, minutes=30)

Common use: add or subtract a timedelta:

today = date.today()
tomorrow = today + timedelta(days=1)
yesterday = today - timedelta(days=1)
print(tomorrow)
print(yesterday)

A simple reminder system example:

event = datetime(2025, 5, 10, 9, 0)
reminder_time = event - timedelta(hours=1)
print("Reminder at:", reminder_time)

Formatting dates and times as strings

Often you need to show a date/time to a user in a friendly format (for example, “01/04/2025 10:30 AM”) or save it in a particular pattern. This is done with strftime (“string format time”).

`strftime` basics

You call .strftime(format_string) on a date or datetime object. The format_string contains special codes that represent parts of the date/time.

Common codes:

Examples

from datetime import datetime
now = datetime.now()
# Simple date
print(now.strftime("%Y-%m-%d"))       # 2025-03-15
# Day/Month/Year
print(now.strftime("%d/%m/%Y"))       # 15/03/2025
# Full date with words
print(now.strftime("%A, %B %d, %Y"))
# e.g. Saturday, March 15, 2025
# Time in 24-hour format
print(now.strftime("%H:%M:%S"))       # 14:30:05
# Time in 12-hour format with AM/PM
print(now.strftime("%I:%M %p"))       # 02:30 PM

You can mix text and codes:

message = now.strftime("Backup created on %Y-%m-%d at %H:%M")
print(message)

Turning strings into dates and times (`strptime`)

Sometimes you receive a date/time as a string (for example, from user input or a file) and you want to convert it into a datetime object. Use strptime (“string parse time”).

You must tell Python what pattern the string follows, using the same codes as strftime.

Basic usage

from datetime import datetime
text = "2025-04-01 10:30"
dt = datetime.strptime(text, "%Y-%m-%d %H:%M")
print(dt)            # 2025-04-01 10:30:00
print(type(dt))      # <class 'datetime.datetime'>

Another example with different format

birthday_text = "20/05/2000"
birthday = datetime.strptime(birthday_text, "%d/%m/%Y")
print(birthday.date())    # 2000-05-20

Common mistake: the format string must match exactly the input string.

For example, this will fail:

text = "2025/04/01"
# Wrong: using '-' instead of '/'
# dt = datetime.strptime(text, "%Y-%m-%d")  # ValueError
# Correct:
dt = datetime.strptime(text, "%Y/%m/%d")

Simple practical examples

Countdown until a future date

from datetime import date
today = date.today()
holiday = date(2025, 12, 25)
days_left = (holiday - today).days
print("Days until holiday:", days_left)

Adding days to a date (e.g. due date)

from datetime import date, timedelta
borrow_date = date.today()
loan_period = timedelta(days=14)
due_date = borrow_date + loan_period
print("Borrow date:", borrow_date)
print("Due date:", due_date)

Logging with timestamps

from datetime import datetime
def log(message):
    now = datetime.now()
    timestamp = now.strftime("%Y-%m-%d %H:%M:%S")
    print(f"[{timestamp}] {message}")
log("Program started")
log("Something happened")

This produces output like:

[2025-03-15 14:45:10] Program started
[2025-03-15 14:45:11] Something happened

Summary

These tools cover most everyday tasks involving dates and times in Python and are often enough for simple scripts, logs, reminders, and basic scheduling.

Views: 143

Comments

Please login to add a comment.

Don't have an account? Register now!