Dates in Python datetime, strftime, timedelta is an important Python topic because it appears in real projects, debugging sessions, and interviews. Learn the meaning first, then connect it to a small working example so the rule does not stay abstract.
For this page, focus on what problem Dates in Python datetime, strftime, timedelta solves, where developers usually make mistakes, and how to verify the result. The audit note for this lesson was: under 650 content words; limited checklist/practice/mistake/FAQ notes .
A strong understanding of Dates in Python datetime, strftime, timedelta should include syntax, behavior, one realistic use case, one failure case, and one quick way to check your work with tools or output.
Dates in Python datetime strftime timedelta should be studied as a practical Python lesson, not as a label. Start by naming the input, the rule that changes the input, and the result a learner should be able to predict after reading the page.
In the python > dates page, the notes should connect the definition with a working scenario, a mistake that beginners actually make, and the exact check that proves the fix. That makes the topic useful for coding, debugging, and interview revision.
Python's built-in datetime module provides classes for working with dates and times. The main classes are date, time, datetime, and timedelta.
from datetime import date, time, datetime
# Current date
today = date.today()
print(today) # 2024-01-15
print(today.year) # 2024
print(today.month) # 1
print(today.day) # 15
# Current date and time
now = datetime.now()
print(now) # 2024-01-15 14:30:45.123456
print(now.hour) # 14
print(now.minute) # 30
print(now.second) # 45
# UTC time
from datetime import timezone
utc_now = datetime.now(timezone.utc)
print(utc_now)
from datetime import date, time, datetime
# Specific date
birthday = date(1990, 6, 15)
print(birthday) # 1990-06-15
# Specific time
alarm = time(7, 30, 0)
print(alarm) # 07:30:00
# Specific datetime
event = datetime(2024, 12, 25, 18, 0, 0)
print(event) # 2024-12-25 18:00:00
# From timestamp (Unix time)
import time as t
ts = datetime.fromtimestamp(t.time())
print(ts)
# From ISO format string
dt = datetime.fromisoformat("2024-06-15T14:30:00")
print(dt)
Use strftime() to format a datetime as a string.
from datetime import datetime
now = datetime(2024, 6, 15, 14, 30, 45)
print(now.strftime("%Y-%m-%d")) # 2024-06-15
print(now.strftime("%d/%m/%Y")) # 15/06/2024
print(now.strftime("%B %d, %Y")) # June 15, 2024
print(now.strftime("%A, %B %d, %Y")) # Saturday, June 15, 2024
print(now.strftime("%I:%M %p")) # 02:30 PM
print(now.strftime("%H:%M:%S")) # 14:30:45
print(now.strftime("%Y-%m-%dT%H:%M:%S")) # ISO 8601
# Common format codes:
# %Y = 4-digit year %m = month (01-12) %d = day (01-31)
# %H = hour (00-23) %M = minute (00-59) %S = second (00-59)
# %I = hour (01-12) %p = AM/PM %A = weekday name
# %B = month name %j = day of year %W = week number
from datetime import datetime
# Parse a date string into a datetime object
dt = datetime.strptime("2024-06-15", "%Y-%m-%d")
print(dt) # 2024-06-15 00:00:00
dt2 = datetime.strptime("June 15, 2024 2:30 PM", "%B %d, %Y %I:%M %p")
print(dt2) # 2024-06-15 14:30:00
# Convert between formats
user_input = "15/06/2024"
parsed = datetime.strptime(user_input, "%d/%m/%Y")
formatted = parsed.strftime("%B %d, %Y")
print(formatted) # June 15, 2024
from datetime import date, datetime, timedelta
today = date.today()
# Add/subtract days
tomorrow = today + timedelta(days=1)
last_week = today - timedelta(weeks=1)
next_month = today + timedelta(days=30)
print(tomorrow) # tomorrow's date
print(last_week) # 7 days ago
print(next_month) # 30 days from now
# Difference between two dates
start = date(2024, 1, 1)
end = date(2024, 12, 31)
diff = end - start
print(diff.days) # 365
# Age calculator
birthday = date(1990, 6, 15)
today = date.today()
age = today.year - birthday.year
if (today.month, today.day) < (birthday.month, birthday.day):
age -= 1
print(f"Age: {age}")
# Time difference
start_time = datetime(2024, 1, 1, 9, 0, 0)
end_time = datetime(2024, 1, 1, 17, 30, 0)
duration = end_time - start_time
print(duration) # 8:30:00
print(duration.seconds) # 30600 seconds
print(duration.seconds // 3600) # 8 hours
When studying Dates in Python datetime, strftime, timedelta, separate three things: the concept, the syntax, and the situation where it is useful. This prevents the lesson from becoming a list of commands with no practical meaning.
In Python, Dates in Python datetime, strftime, timedelta becomes easier when you build a tiny example first, then increase complexity. Add one realistic input, one invalid or boundary input, and one explanation of why the result changes.
def review_dates-in-python-datetime-strftime-timedelta():
value = "sample"
if value:
print("Dates in Python datetime strftime timedelta: normal path is ready")
else:
print("Dates in Python datetime strftime timedelta: handle the empty path first")
review_dates-in-python-datetime-strftime-timedelta()
items = []
if not items:
print("Dates in Python datetime strftime timedelta: no data available, show a fallback")
else:
print(items[0])
Memorizing Dates in Python datetime strftime timedelta without the situation where it is useful.
Connect Dates in Python datetime strftime timedelta to a concrete Python task.
Testing Dates in Python datetime strftime timedelta only with the perfect input.
Include empty, missing, duplicate, incompatible, or failed cases when relevant.
Changing code before reading the visible symptom or error message.
Inspect the output, state, configuration, or stack trace connected to Dates in Python datetime strftime timedelta.
Memorizing Dates in Python datetime strftime timedelta without the situation where it is useful.
Connect Dates in Python datetime strftime timedelta to a concrete Python task.
The common mistake is memorizing syntax without understanding when the behavior changes or fails.
Remember the problem it solves in Python, then attach the syntax or steps to that problem.
You can predict the result of a small example, explain a failure case, and choose it over a nearby alternative for a clear reason.
They often copy the syntax but skip the state, input, dependency, selector, route, type, or configuration that controls the behavior.
Explore 500+ free tutorials across 20+ languages and frameworks.