Date and Time in Python: Work with Time Data Correctly
Introduction
In this chapter, you will learn how to handle date and time in Python using the datetime module. Time handling is essential for logs, scheduling, deadlines, and reports. Once you understand these basics, your programs can process real-world time data in a reliable way.
Prerequisites
- Python
3.10+installed - Basic understanding of functions, strings, and file handling
- Ability to run
.pyfiles in terminal or IDE
Why Date and Time Matter
Many practical tasks depend on time:
- recording user actions
- generating daily reports
- checking expiration and deadlines
- measuring task duration
1) datetime Basics
Import from Python's built-in datetime module.
from datetime import datetime
# Get current local date and time
now = datetime.now()
print(now)You can access components:
from datetime import datetime
now = datetime.now()
print(now.year)
print(now.month)
print(now.day)
print(now.hour)
print(now.minute)
print(now.second)2) date and time Objects
Use dedicated objects when you only need date or only time.
from datetime import date, time
# Create date object
today = date.today()
print(today)
# Create time object
t = time(14, 30, 0)
print(t)3) Format DateTime with strftime()
Convert datetime object to readable string.
from datetime import datetime
now = datetime.now()
# Format: 2026-05-08 23:06:00
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted)Common format symbols:
%Yyear (4 digits)%mmonth (01-12)%dday (01-31)%Hhour (00-23)%Mminute (00-59)%Ssecond (00-59)
4) Parse String to DateTime with strptime()
Convert text into datetime object.
from datetime import datetime
text = "2026-05-08 21:30:00"
dt = datetime.strptime(text, "%Y-%m-%d %H:%M:%S")
print(dt)Useful when reading timestamps from user input or files.
Tip
Format Safety
strptime() format must match input text exactly, otherwise a ValueError is raised.
5) Time Arithmetic with timedelta
Use timedelta for adding or subtracting time.
from datetime import datetime, timedelta
now = datetime.now()
# Add 7 days
next_week = now + timedelta(days=7)
# Subtract 2 hours
two_hours_ago = now - timedelta(hours=2)
print("Now:", now)
print("Next week:", next_week)
print("Two hours ago:", two_hours_ago)This is useful for deadline and duration logic.
6) Measure Program Duration
You can calculate elapsed time between two timestamps.
from datetime import datetime
import time
start = datetime.now()
time.sleep(1.5)
end = datetime.now()
duration = end - start
print("Duration:", duration)
print("Total seconds:", duration.total_seconds())7) Real Mini Example: Study Session Logger
This example records study start time, end time, and duration.
from datetime import datetime
# Mark start time
start = datetime.now()
print("Study started at:", start.strftime("%Y-%m-%d %H:%M:%S"))
input("Press Enter when study session ends...")
# Mark end time
end = datetime.now()
print("Study ended at:", end.strftime("%Y-%m-%d %H:%M:%S"))
# Compute duration
duration = end - start
minutes = duration.total_seconds() / 60
print(f"Study duration: {minutes:.2f} minutes")This pattern appears in timers, productivity tools, and audit logs.
Warning
Do not compare or store date/time only as plain strings when arithmetic is needed.
Convert to datetime objects first for reliable operations.
Common Beginner Mistakes
Mistake 1: Confusing %m and %M
%m is month, %M is minute.
Mistake 2: Parsing with Wrong Format String
Even small mismatches (like / vs -) cause parsing errors.
Mistake 3: Doing Time Math on Strings
Always parse to datetime before adding/subtracting.
Surprise Practice Challenge
Build a "Deadline Reminder Tool":
- Ask user to input a deadline datetime (
YYYY-MM-DD HH:MM:SS) - Parse input with
strptime() - Compare with current time
- Print remaining days/hours/minutes
- If deadline passed, print overdue duration
If you finish this, you can already implement many practical scheduling features.
FAQ
Should I use time module or datetime module?
For calendar-style date/time logic, prefer datetime. Use time for low-level timing utilities.
Why does strptime() fail often for beginners?
Because format strings must match input exactly.
Can I store datetime in files?
Yes. A common way is storing formatted strings (for example ISO style) and parsing them when needed.
How do I get current date only?
Use date.today() or datetime.now().date().