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

Python datetime Module

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

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")
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)
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)
meeting = time(14, 30)
print(birthday, meeting)

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.