Dates and Times in Python with datetime
Work with dates and times in Python using the datetime module: get today, build specific dates, find differences with timedelta, and format dates with strftime.
Key takeaways
- The datetime module handles dates and times so you do not have to count days yourself
- datetime.now() gives the current date and time; date.today() gives just today's date
- Subtracting two dates gives a timedelta you can read in days
- strftime turns a date into formatted text using codes like %Y, %m and %d
Why a special module for dates?
Dates look simple but hide nasty traps: months have different lengths, leap years exist, and "30 days from now" might land in a new month. Counting all that by hand is painful and error-prone. Python's built-in datetime module does the hard arithmetic for you.
This lesson assumes you understand using Python libraries and basic Python numbers and math.
Getting today's date and time
from datetime import datetime, date
now = datetime.now()
print(now) # 2026-05-30 14:23:05.123456
today = date.today()
print(today) # 2026-05-30
Line by line:
from datetime import datetime, dateimports the two classes we need. (The module and one of its classes share the namedatetime, which is why the import looks repetitive.)datetime.now()returns the current moment, including the time.date.today()returns just the calendar date, with no time attached.
You can also pull out individual pieces:
print(now.year) # 2026
print(now.month) # 5
print(now.day) # 30
print(now.hour) # 14
Each attribute is a normal integer you can use in calculations or comparisons.
Building a specific date
To make a date of your choosing, pass year, month and day:
from datetime import date
birthday = date(2010, 7, 15)
print(birthday) # 2010-07-15
print(birthday.year) # 2010
date(2010, 7, 15) means 15 July 2010. The order is always year, month, day.
Finding the gap between two dates
Subtracting one date from another gives a timedelta, an object that represents a span of time.
from datetime import date
start = date(2026, 1, 1)
end = date(2026, 12, 25)
gap = end - start
print(gap) # 358 days, 0:00:00
print(gap.days) # 358
end - startproduces a timedelta.gap.daysextracts the difference as a whole number of days. Python handled every month length and any leap year for you.
This is perfect for "how many days until..." style features.
Adding and subtracting time
A timedelta also lets you move a date forward or backward.
from datetime import date, timedelta
today = date(2026, 5, 30)
one_week_later = today + timedelta(days=7)
print(one_week_later) # 2026-06-06
ten_days_ago = today - timedelta(days=10)
print(ten_days_ago) # 2026-05-20
timedelta(days=7) is "seven days of duration". Adding it rolls the date into June automatically, crossing the end of May without any effort from you. You can also pass weeks, hours, minutes and seconds.
Formatting dates with strftime
A raw date like 2026-05-30 is fine for computers, but you often want something friendlier. strftime (string-format-time) turns a date into text using format codes:
from datetime import datetime
now = datetime(2026, 5, 30, 14, 5)
print(now.strftime("%d/%m/%Y")) # 30/05/2026
print(now.strftime("%A, %d %B %Y")) # Saturday, 30 May 2026
print(now.strftime("%H:%M")) # 14:05
The common codes:
| Code | Meaning | Example |
|---|---|---|
%Y | Four-digit year | 2026 |
%m | Two-digit month | 05 |
%d | Two-digit day | 30 |
%B | Full month name | May |
%A | Full weekday name | Saturday |
%H | Hour (24-hour) | 14 |
%M | Minute | 05 |
You arrange the codes and any punctuation however you like, and strftime fills in the values.
Worked example: a countdown to an event
Let's calculate how many days remain until a future event and print a tidy message.
from datetime import date
def days_until(year, month, day):
today = date.today()
event = date(year, month, day)
gap = event - today
return gap.days
remaining = days_until(2026, 12, 25)
print(f"There are {remaining} days until 25 December 2026.")
Step by step:
date.today()gets the current date.date(year, month, day)builds the event date from the arguments.event - todayproduces a timedelta;.daysgives the whole-day count.- The f-string prints a clean message. (F-strings are explained in f-strings and string formatting in Python.)
If today is 30 May 2026, this reports roughly 209 days until Christmas. Run it tomorrow and the number drops by one — without you changing a thing.
Common mistakes
- Wrong argument order.
date(15, 7, 2010)is invalid because month 7 is fine but "day 2010" and "year 15" make no sense. Always year, month, day. - Confusing
dateanddatetime. Calling.houron a plaindatefails because a date has no time part. - Forgetting timedelta for arithmetic. You cannot add a plain number to a date; you must add a
timedelta. - Mixing up
%mand%M. Lowercase%mis the month; uppercase%Mis the minute.
Try it yourself
- Print today's date in the format
Day-Month-Year, for example30-May-2026. - Write a function that takes someone's birth date and returns their age in whole days.
- Print the date exactly 100 days from today using
timedelta.
Once you can manipulate dates, combine them with stored data by reading and writing them in files via working with JSON in Python.
Quick quiz
Test yourself and earn XP
Which function gives the current date and time?
datetime.now() returns the current date and time as a datetime object.
What do you get when you subtract one date from another?
Subtracting dates produces a timedelta, which stores the difference and exposes it as days and seconds.
What does strftime do?
strftime (string-format-time) converts a date into a human-readable string using format codes.
In strftime, what does %Y mean?
%Y is the full four-digit year, such as 2026. Lowercase %y would be the two-digit version.
Which class would you import to add 7 days to a date?
timedelta represents a span of time, so adding timedelta(days=7) moves a date forward one week.
FAQ
No. datetime is part of Python's standard library, so a simple from datetime import datetime is all you need.
A date holds only year, month and day. A datetime also holds the time of day - hours, minutes and seconds. Use whichever your task needs.
Each code stands for one piece of a date or time, like %Y for the year or %H for the hour. You combine them to design exactly the format you want.
Keep exploring
More in Coding