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.

Parsing Text into Dates with strptime

Formatting turns a date into text; parsing goes the other way. Real datasets store dates as strings, so strptime() is how you turn them into objects you can calculate with. You describe the layout of the text with format codes:

from datetime import datetime

order_time = datetime.strptime("05/03/2025 18:45", "%d/%m/%Y %H:%M")
print(order_time.year, order_time.month, order_time.hour)   # 2025 3 18

iso = datetime.fromisoformat("2025-03-05T18:45:00")
print(iso == order_time)   # True
CodeMeaningExample
%dDay of the month, two digits05
%mMonth number, two digits03
%b / %BShort or full month nameMar / March
%Y / %yFour-digit or two-digit yearfull / short form
%H / %IHour in 24-hour or 12-hour clock18 / 06
%MMinutes45
%pAM or PMPM

If the text does not match the format exactly, Python raises a ValueError. That is helpful: it tells you a row is in an unexpected format instead of silently producing a wrong date.

Date Arithmetic and Time Zones

A timedelta can be added to or subtracted from a date to move forward or backward in time. It works in days, seconds and microseconds, and also accepts weeks, hours and minutes.

from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo

placed = datetime.now()
delivery = placed + timedelta(days=5)
reminder = delivery - timedelta(hours=12)

# Time-zone-aware timestamps
now_utc = datetime.now(timezone.utc)
now_india = now_utc.astimezone(ZoneInfo("Asia/Kolkata"))
print(now_india.strftime("%d %b, %I:%M %p %Z"))   # e.g. 05 Mar, 06:45 PM IST

A datetime without time-zone information is called naive; one with it is aware. Data collected from users or servers in different regions should be stored as aware timestamps, ideally in UTC, and converted to local time only for display.

Note that timedelta has no "months" option, because months have different lengths. For month-based steps, use a library such as dateutil with its relativedelta, or Pandas date offsets.

Mistakes to Avoid and Tips for Data Work

  • Mixing up %m and %M. Lowercase %m is the month and uppercase %M is minutes. Swapping them gives strange but valid-looking dates.
  • Comparing naive and aware values. Python raises a TypeError. Make both sides aware, or both naive, before comparing.
  • Using datetime.utcnow(). It returns a naive value and is deprecated in recent Python versions. Use datetime.now(timezone.utc) instead.
  • Guessing day-first or month-first. "04/05" can mean 4 May or 5 April. Confirm the convention with whoever supplied the data.

For whole columns in a DataFrame, pd.to_datetime(df["order_date"], format="%d/%m/%Y") converts thousands of strings at once. Adding errors="coerce" turns unparseable entries into missing values, so you can count and inspect them instead of crashing. After converting, the .dt accessor gives quick access to parts such as .dt.month or .dt.day_name(), which are handy features for analysis and machine learning.

Ready to Master Data Science?

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

Explore Course