Order dates, joining dates, batch start dates, log timestamps: real programs are full of dates. Treating them as plain text causes bugs, such as sorting “10/2” before “9/2”. Python’s built-in datetime module handles dates properly.
Getting today’s date and time
from datetime import date, datetime, timedelta
today = date.today()
now = datetime.now()
date holds only the day; datetime also holds the time.
Formatting dates as text
Use strftime() with format codes: today.strftime("%d %b %Y") gives something like “19 Nov 2026”. Common codes: %d day, %m month number, %b short month name, %Y four-digit year, %H:%M hours and minutes.
Reading dates from text
The reverse is strptime(): datetime.strptime("19-11-2026", "%d-%m-%Y"). The format must match the text exactly, or Python raises a ValueError. Indian data often uses day-month-year, while many tools default to month-day-year, so always check which one your file uses.
Date arithmetic
timedelta represents a duration:
today + timedelta(days=30)gives the date 30 days from now.- Subtracting two dates gives a timedelta:
(end - start).daysis the number of days between them. - Comparing dates works with normal operators:
if due_date < today:.
Time zones
datetime.now() has no time zone attached. For apps used across regions, store times in UTC and convert for display, for example with zoneinfo.ZoneInfo("Asia/Kolkata"). Django handles this for you when USE_TZ = True.
Dates in pandas
For data analysis, convert a column once with pd.to_datetime(df["order_date"], dayfirst=True), then use .dt.month or .dt.day_name() to group by month or weekday.
Practise by writing a function that returns how many days are left until a given date. Related: Python string methods and Python functions for beginners.
These topics are practised with projects in our Python Full Stack course in Bangalore.
Book a free demo class at our BTM Layout centre, and ask a counsellor for batch details.
