Date Time Module

The datetime module lets you work with dates and times in Python - creating them, formatting them for display, and calculating the difference between two points in time.

Getting the Current Date and Time

import datetime

today = datetime.date.today()
print(today)   # e.g. 2026-07-15

now = datetime.datetime.now()
print(now)     # e.g. 2026-07-15 14:32:10.123456

Formatting Dates with strftime

The strftime() method converts a datetime object into a custom, human-readable string format.

now = datetime.datetime.now()
print(now.strftime("%d-%m-%Y"))       # 15-07-2026
print(now.strftime("%A, %B %d, %Y"))  # Wednesday, July 15, 2026

Calculating Time Differences

Subtracting two datetime objects produces a timedelta object, representing the duration between them.

from datetime import date

start = date(2026, 1, 1)
end = date(2026, 7, 15)
difference = end - start

print(difference.days)   # number of days between the two dates
When working with data that includes timestamps, always check whether your dataset uses a consistent date format before parsing - real-world date data is notoriously inconsistent and often needs cleaning before it can be converted into proper datetime objects.

Coming Up Next

Next, you'll explore the random module - used for generating random numbers and making random selections in Python.

Ready to Master Data Science?

Join Uncodemy's Data Science Course and build real, job-ready skills with expert mentors.

Explore Course