← Back to Chapters

Python Dates

?️ Python Dates

⚡ Quick Overview

Python provides the datetime module to work with dates and times. Using this module, you can: get the current date and time, create specific date objects (like birthdays), access individual components (year, month, day), format dates into readable strings, and perform date arithmetic such as adding days or finding the difference between two dates.

? Key Concepts

  • datetime module – main module for handling dates and times in Python.
  • datetime.datetime – represents both date and time together.
  • datetime.date – represents only a date (year, month, day).
  • datetime.timedelta – represents a duration or difference between two dates/times.
  • strftime() – formats a date/time object into a readable string.
  • date.today() and datetime.now() – get the current date or current date & time.

? Syntax and Theory

To use dates in Python, you first import the built-in datetime module. From this module you can create objects of type date, datetime, and use timedelta to do arithmetic (add/subtract days, weeks, seconds, etc.).

Once you have a date or datetime object, you can access attributes like year, month, and day, and you can format it using strftime(format_string) where the format string uses special codes like %Y (year), %m (month), %d (day), %A (weekday name), etc.

? Code Examples

? Importing datetime Module

? View Code Example
import datetime

current_time = datetime.datetime.now()
print(current_time)  # e.g., 2025-09-11 20:45:00.123456

? Creating Date Objects

? View Code Example
import datetime

# year, month, day
birthday = datetime.date(1995, 7, 20)
print(birthday)  # 1995-07-20

⏰ Accessing Date Components

? View Code Example
import datetime

today = datetime.datetime.now()
print(today.year)   # 2025
print(today.month)  # 9
print(today.day)    # 11

? Formatting Dates with strftime()

Use the strftime() method to format dates into readable strings.

? View Code Example
import datetime

today = datetime.datetime.now()
print(today.strftime("%A, %d %B %Y"))
# Example: Thursday, 11 September 2025

➕➖ Date Arithmetic with timedelta

? View Code Example
import datetime

today = datetime.date.today()  # get today's date
tomorrow = today + datetime.timedelta(days=1)  # add one day
yesterday = today - datetime.timedelta(days=1)  # subtract one day

# display today, tomorrow, and yesterday
print("Today:", today)
print("Tomorrow:", tomorrow)
print("Yesterday:", yesterday)

⏳ Measuring Time Difference

? View Code Example
import datetime

start = datetime.datetime(2025, 1, 1)  # start date
end = datetime.datetime(2025, 12, 31)  # end date

difference = end - start  # time difference as timedelta
print("Days between:", difference.days)  # print number of days

? Live Output / Explanation

?️ What the Code Does

  • Current date & time: datetime.datetime.now() prints the system’s current date and time, including microseconds.
  • Date objects: datetime.date(1995, 7, 20) creates a date object for 20 July 1995 and prints it as 1995-07-20.
  • Components: From a datetime object, today.year, today.month, and today.day extract the individual parts.
  • Formatted output: strftime("%A, %d %B %Y") might produce something like Thursday, 11 September 2025, which is more human-friendly.
  • Date arithmetic: Using today + datetime.timedelta(days=1) gives tomorrow, and subtracting 1 day gives yesterday.
  • Difference between dates: Subtracting two datetime objects gives a timedelta. Access .days to find how many days are between them.

? Use Cases

  • Building countdowns (e.g., days left until exams or New Year).
  • Logging events with accurate timestamps.
  • Scheduling tasks or reminders on specific dates.
  • Calculating age, membership duration, or project deadlines.

? Tips & Best Practices

  • Use strftime() for readable date formatting before showing dates to users.
  • timedelta is ideal for adding or subtracting days, weeks, or seconds from a date.
  • date.today() returns only the date (no time), which is often enough for many apps.
  • When doing arithmetic, keep types consistent (work with date to date or datetime to datetime).

? Try It Yourself

  • Create a program that prints today’s date in format DD/MM/YYYY using strftime().
  • Ask the user for their birth date and calculate their exact age in days using date and timedelta.
  • Write a countdown program that shows days left until New Year using the current date and a fixed New Year date.