📅
Coding🎓 Ages 14-18Intermediate 10 min read

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, date imports the two classes we need. (The module and one of its classes share the name datetime, 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 - start produces a timedelta.
  • gap.days extracts 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:

CodeMeaningExample
%YFour-digit year2026
%mTwo-digit month05
%dTwo-digit day30
%BFull month nameMay
%AFull weekday nameSaturday
%HHour (24-hour)14
%MMinute05

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 - today produces a timedelta; .days gives 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 date and datetime. Calling .hour on a plain date fails 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 %m and %M. Lowercase %m is the month; uppercase %M is the minute.

Try it yourself

  1. Print today's date in the format Day-Month-Year, for example 30-May-2026.
  2. Write a function that takes someone's birth date and returns their age in whole days.
  3. 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?

What do you get when you subtract one date from another?

What does strftime do?

In strftime, what does %Y mean?

Which class would you import to add 7 days to a date?

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.