Date & Time
Learn how to work with dates and times in Python using the datetime module, including formatting, parsing, and date arithmetic.
Introduction
Almost every real program eventually needs to deal with dates and times — logging when something happened, calculating someone's age, scheduling a reminder, or measuring how long a task took. Handling this manually with plain numbers is error-prone, since months have different lengths and years can be leap years.
Python's built-in datetime module handles all of this complexity for you. This lesson covers how to get the current date and time, build specific dates, format and parse them, and perform date arithmetic.
- How to get the current date and time with datetime.now().
- How to build a specific date using datetime(year, month, day).
- How to format dates into strings with strftime().
- How to parse strings into dates with strptime().
- How to add or subtract time using timedelta.
- The difference between the date, time, and datetime classes.
The datetime Module
The datetime module is part of Python's standard library, so no installation is required — just import it. It provides several classes for working with dates and times, the most commonly used being datetime itself.
from datetime import datetime
print(type(datetime.now()))<class 'datetime.datetime'>date
Represents a calendar date only: year, month, day.
time
Represents a time of day only: hour, minute, second, microsecond.
datetime
Combines date and time into a single object.
timedelta
Represents a duration — the difference between two dates or times.
Getting the Current Date and Time
datetime.now() returns a datetime object representing the current moment, including the date and time down to microseconds.
from datetime import datetime
current = datetime.now()
print(current)
print(current.year, current.month, current.day)
print(current.hour, current.minute, current.second)2026-07-25 09:41:12.583201
2026 7 25
9 41 12The exact numbers will differ every time you run this, since it reflects the moment the code executes. Each part of the date and time is available as a separate attribute on the object.
Creating a Specific Date
You are not limited to "right now" — you can build a datetime object for any date and time by passing the year, month, and day (and optionally hour, minute, second) directly.
from datetime import datetime
launch_day = datetime(2026, 1, 1)
print(launch_day)
meeting = datetime(2026, 3, 15, 14, 30)
print(meeting)2026-01-01 00:00:00
2026-03-15 14:30:00If you omit the time, it defaults to midnight (00:00:00). This is useful when you only care about the date and not a specific time.
date, time, and datetime: When to Use Which
Sometimes you only need a calendar date without a time, or a time of day without a specific date. The datetime module provides date and time classes for exactly these cases.
from datetime import date, time, datetime
just_date = date(2026, 12, 25)
print(just_date)
just_time = time(18, 30, 0)
print(just_time)
combined = datetime.combine(just_date, just_time)
print(combined)2026-12-25
18:30:00
2026-12-25 18:30:00date
Use when you only care about the calendar day — e.g. a birthday or a deadline.
time
Use when you only care about the clock time — e.g. "store opens at 09:00".
datetime
Use when you need both together — e.g. "logged in at 2026-03-15 14:30".
Formatting Dates with strftime()
strftime() ("string format time") converts a datetime object into a custom-formatted string, using special codes to represent each part of the date.
%Y
4-digit year, e.g. 2026.
%m
2-digit month, e.g. 07.
%d
2-digit day, e.g. 25.
%H:%M:%S
Hour, minute, second in 24-hour format.
%B
Full month name, e.g. July.
%A
Full weekday name, e.g. Saturday.
from datetime import datetime
now = datetime(2026, 7, 25, 9, 41)
print(now.strftime("%Y-%m-%d"))
print(now.strftime("%d/%m/%Y"))
print(now.strftime("%B %d, %Y"))
print(now.strftime("%A, %H:%M"))2026-07-25
25/07/2026
July 25, 2026
Saturday, 09:41Parsing Strings with strptime()
strptime() ("string parse time") does the opposite of strftime() — it converts a string into a datetime object, as long as you tell it exactly what format the string is in.
from datetime import datetime
text = "25-07-2026"
parsed = datetime.strptime(text, "%d-%m-%Y")
print(parsed)
print(type(parsed))2026-07-25 00:00:00
<class 'datetime.datetime'>The format string passed to strptime() must match the layout of the input string exactly, or Python raises a ValueError.
from datetime import datetime
try:
datetime.strptime("25-07-2026", "%Y-%m-%d")
except ValueError as e:
print("Error:", e)Error: time data '25-07-2026' does not match format '%Y-%m-%d'Date Arithmetic with timedelta
A timedelta object represents a span of time — like "3 days" or "2 hours." You can add or subtract a timedelta from a datetime to shift it forward or backward, and subtracting two datetime objects gives you a timedelta automatically.
from datetime import datetime, timedelta
today = datetime(2026, 7, 25)
next_week = today + timedelta(days=7)
print("One week later:", next_week)
last_month = today - timedelta(days=30)
print("30 days earlier:", last_month)One week later: 2026-08-01 00:00:00
30 days earlier: 2026-06-25 00:00:00from datetime import datetime
start = datetime(2026, 1, 1)
end = datetime(2026, 7, 25)
difference = end - start
print(difference)
print("Days between:", difference.days)Days between: 205
205 days, 0:00:00timedelta accepts days, seconds, microseconds, milliseconds, minutes, hours, and weeks — all as keyword arguments, e.g. timedelta(weeks=2, hours=3).
Common Mistakes
- Mixing up the format codes between strftime() and strptime() — they use the same codes but opposite directions.
- Assuming strptime() can guess the format — it must match the input string exactly.
- Forgetting that datetime.now() includes microseconds, which can make direct string comparisons fail.
- Trying to add a plain number of days to a datetime instead of wrapping it in timedelta(days=...).
- Confusing date (no time) with datetime (date and time) when a time component is actually needed.
Best Practices
- Use strftime() whenever you need to display a date to a user in a specific format.
- Use strptime() when reading dates from user input, files, or APIs.
- Prefer timedelta for any date math instead of manually calculating days per month.
- Store dates as datetime objects internally, and only convert to strings for display.
- Double-check AM/PM formatting with %I and %p if you need 12-hour time instead of 24-hour.
Frequently Asked Questions
What is the difference between date and datetime?
date represents only a calendar day (year, month, day). datetime represents both a calendar day and a time of day (hour, minute, second, microsecond).
How do I get just today's date without the time?
Use date.today() from the datetime module, or call .date() on a datetime object, e.g. datetime.now().date().
Why did my strptime() call raise a ValueError?
The format string you passed does not match the actual layout of the input string. Check that the order and punctuation of %Y, %m, %d, etc. line up exactly with your text.
Can timedelta represent months or years?
No, timedelta only supports days, weeks, hours, minutes, seconds, and smaller units, because months and years vary in length. For calendar-aware math, the third-party dateutil library is commonly used.
How do I find the difference between two dates in days?
Subtract one datetime from another to get a timedelta, then read its .days attribute, e.g. (end - start).days.
Key Takeaways
- The datetime module provides date, time, datetime, and timedelta classes.
- datetime.now() returns the current date and time.
- datetime(year, month, day) builds a specific date.
- strftime() converts a datetime into a formatted string; strptime() does the reverse.
- timedelta represents a duration and lets you add, subtract, and compare dates.
Summary
The datetime module gives Python a reliable, built-in way to represent, format, parse, and calculate with dates and times, without needing to manually account for varying month lengths or leap years.
In this lesson, you learned how to get the current date and time, build specific dates, format and parse dates as strings, and perform date arithmetic using timedelta.
- You can retrieve and construct dates and times using datetime.
- You can format dates to strings and parse strings back into dates.
- You can perform date arithmetic using timedelta.
- You are ready to explore Python's math module.