LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 4826 min read

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.

What You Will Learn
  • 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()))
Output

Click Run to see what this code prints.

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)
Output

Click Run to see what this code prints.

The 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)
Output

Click Run to see what this code prints.

If 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)
Output

Click Run to see what this code prints.

date

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"))
Output

Click Run to see what this code prints.

Parsing 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))
Output

Click Run to see what this code prints.

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)
Output

Click Run to see what this code prints.

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)
Output

Click Run to see what this code prints.

from datetime import datetime
start = datetime(2026, 1, 1)
end = datetime(2026, 7, 25)
difference = end - start
print(difference)
print("Days between:", difference.days)
Output

Click Run to see what this code prints.

timedelta Arguments

timedelta accepts days, seconds, microseconds, milliseconds, minutes, hours, and weeks — all as keyword arguments, e.g. timedelta(weeks=2, hours=3).

Common Mistakes

Avoid These 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

date represents only a calendar day (year, month, day). datetime represents both a calendar day and a time of day (hour, minute, second, microsecond).

Use date.today() from the datetime module, or call .date() on a datetime object, e.g. datetime.now().date().

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.

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.

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.

Lesson Completed
  • 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.
Next Lesson →

Math Module