← Back to Python Course | Chapter 12: Standard Library | Lesson 5 of 9

Python datetime Module

The datetime module helps your program work with dates and times, like a calendar and clock combined. You can get today's date, format it, or find the days between two dates.
Syntax
python
from datetime import datetime, timedelta

now = datetime.now()
now.strftime("format_code")
now + timedelta(days=n)

Getting Current Date and Time

The datetime module models calendar dates and times as proper objects rather than raw numbers or strings, making date arithmetic and comparisons safe and readable.

datetime.now() returns a datetime object representing the current moment in your system's local time zone (naive, with no time zone attached unless you explicitly add one).

Example: Getting Current Date and Time

python
from datetime import datetime
now = datetime.now()  # current local date and time
print(type(now))

Formatting Dates with strftime

strftime() converts a datetime object into a custom-formatted string using format codes like %Y for a 4-digit year, %m for a zero-padded month, and %d for the day -- the mnemonic is 'string format time'.

This is how you control exactly what a date looks like when displaying it to users or writing it to a file.

Example: Formatting Dates with strftime

python
from datetime import datetime
d = datetime(2024, 3, 15)
print(d.strftime("%Y-%m-%d"))  # formats the datetime as a custom string

Parsing Strings with strptime

strptime() does the reverse: it parses a text string into a datetime object according to a format string you provide that must match the input's layout exactly.

This is essential when reading dates that arrive as plain text, from CSV files, web form submissions, or external APIs.

Example: Parsing Strings with strptime

python
from datetime import datetime
d = datetime.strptime("2024-03-15", "%Y-%m-%d")  # parses text into a datetime using the given format
print(d.year, d.month, d.day)

Calculating Time Differences

A timedelta object represents a span of time -- days, seconds, or microseconds -- rather than a specific point in time.

Adding or subtracting a timedelta from a datetime computes a new date shifted forward or backward, which is how you calculate things like 'the date 30 days from now.'

Example: Calculating Time Differences

python
from datetime import datetime, timedelta
d = datetime(2024, 1, 1)
future = d + timedelta(days=30)  # shifts the date 30 days forward
print(future)

Date and Time Objects

The module also provides standalone date and time classes for when you only care about the calendar date or the time of day in isolation, rather than a combined instant.

Using the narrower type documents your intent clearly -- a birthday needs only a date, not a full datetime with an arbitrary time attached.

Example: Date and Time Objects

python
from datetime import date, time
birthday = date(2000, 5, 20)  # calendar date only
meeting = time(14, 30)  # time of day only
print(birthday, meeting)
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using strftime and strptime with mismatched format codes, such as %m for minutes, when %M is minutes and %m is month.
  2. Subtracting two dates and expecting a number, when the result is a timedelta; use .days or .total_seconds().
  3. Mixing timezone-aware and naive datetimes, which raises TypeError when you compare or subtract them.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.