Python Dates
Python · Working with Data
Theory
The datetime module represents dates and times. datetime(2026, 7, 11) creates a specific moment, datetime.now() gives the current local time, and date holds a calendar date without a time. A timedelta is a duration; adding timedelta(days=30) to a date moves it 30 days forward, and subtracting two dates gives a timedelta.
To turn a date into text use strftime() with format codes: %d day, %m month number, %b short month name, %Y four-digit year, %A weekday name. So d.strftime('%d-%b-%Y') gives '11-Jul-2026'. The reverse, datetime.strptime('11-07-2026', '%d-%m-%Y'), parses text into a datetime. Think 'f' for format (to string) and 'p' for parse (from string).
Why we use it
Real data is full of dates - order dates, joining dates, timestamps. datetime lets you parse them, compare them, do arithmetic like 'due in 30 days' and print them in whatever format a report needs.
When to use it
Use datetime for individual dates in plain Python. For whole columns of dates in a DataFrame, pandas' pd.to_datetime() and the .dt accessor are faster and more convenient.
How it works
- Start with text '11-07-2026' or values
- Is the input text? Yes: Parse with datetime.strptime(text, fmt). No: Build with datetime(y, m, d).
- Do arithmetic with timedelta if needed
- Format output with strftime(fmt)
- Readable date string such as '11-Jul-2026'
Syntax
from datetime import datetime
datetime.now()Example
d = datetime(2026, 7, 11)
d.strftime('%d-%b-%Y')Key points
- strftime() formats a date as text
- strptime() parses text into a datetime
- timedelta supports date arithmetic
- Subtracting two dates gives a timedelta (.days for the count)
- datetime.now() uses the local clock; be careful with time zones