Skip to main content

Python datetime: Dates, Times, Timezones, and Calculations

Intermediate25 min6 exercises85 XP
0/6 exercises

Think about your phone. It shows the current time, tracks your calendar events, and reminds you about birthdays. Behind the scenes, all of that runs on date and time calculations.

Python's `datetime` module is your toolkit for working with dates, times, and time differences. You can create specific dates, calculate how many days until an event, format dates for display, and parse date strings from user input.

In this tutorial, you'll learn to create dates and times, do arithmetic with timedelta, format dates with strftime, parse strings with strptime, and compare dates. These skills come up constantly in real-world programming.

How Do You Create Dates and Times in Python?

The datetime module has three main types: date (just a date, no time), time (just a time, no date), and datetime (both date and time together). Most of the time, you'll use datetime because it gives you the full picture.

Creating date, time, and datetime objects
Loading editor...

You can access individual parts of a date or datetime using attributes like .year, .month, .day, .hour, .minute, and .second.

Accessing date components
Loading editor...

How Do You Get the Current Date and Time?

Getting the current date and time is one of the most common operations. Python makes it easy with class methods like today() and now().

Getting the current date and time
Loading editor...

How Do You Add or Subtract Days with timedelta?

A timedelta represents a duration: a difference between two dates or times. You can add or subtract a timedelta from a date to get a new date. Think of it as saying "move forward 7 days" or "go back 2 hours."

Adding and subtracting days
Loading editor...

When you subtract one date from another, you get a timedelta that tells you how many days apart they are.

Finding the difference between dates
Loading editor...
Working with hours and minutes
Loading editor...

How Do You Format Dates with strftime?

The default date format like 2024-06-15 is fine for computers, but humans prefer "June 15, 2024" or "15/06/2024." The strftime() method (string format time) lets you control exactly how a date looks.

Formatting dates with strftime
Loading editor...

Here are the most commonly used format codes:

  • %Y - 4-digit year (2024)
  • %m - Month as number (03)
  • %d - Day of month (14)
  • %B - Full month name (March)
  • %b - Short month name (Mar)
  • %A - Full weekday name (Thursday)
  • %a - Short weekday name (Thu)
  • %H - Hour in 24h format (15)
  • %I - Hour in 12h format (03)
  • %M - Minute (09)
  • %S - Second (26)
  • %p - AM or PM

  • How Do You Parse Date Strings with strptime?

    strptime() (string parse time) is the opposite of strftime(). It takes a string and a format, and converts it into a datetime object. This is how you turn user input like "March 14, 2024" into a date Python can work with.

    Parsing date strings
    Loading editor...
    strftime: datetime -> string
    from datetime import datetime
    dt = datetime(2024, 3, 14)
    text = dt.strftime('%B %d, %Y')
    print(text)  # March 14, 2024
    strptime: string -> datetime
    from datetime import datetime
    text = 'March 14, 2024'
    dt = datetime.strptime(text, '%B %d, %Y')
    print(dt)  # 2024-03-14 00:00:00

    How Do You Compare Dates in Python?

    You can compare dates using the standard comparison operators: <, >, <=, >=, ==, and !=. Earlier dates are "less than" later dates. This makes it easy to check if an event is in the past or future.

    Comparing and sorting dates
    Loading editor...
    Checking past vs future dates
    Loading editor...

    Practice Exercises

    Create and Display a Date
    Write Code

    Create a date object for July 4, 2024. Print it in the format July 04, 2024 using strftime.

    Loading editor...
    Calculate Days Between Dates
    Write Code

    Calculate how many days are between January 1, 2024 and March 15, 2024. Print just the number of days.

    Loading editor...
    Add Two Weeks to a Date
    Write Code

    Starting from date(2024, 6, 15), add 14 days using timedelta. Print the result in the default format (YYYY-MM-DD).

    Loading editor...
    Parse a Date String
    Write Code

    Parse the string '15-06-2024' into a datetime object using strptime with the format '%d-%m-%Y'. Then print it reformatted as 'June 15, 2024' using strftime.

    Loading editor...
    Predict the Date Output
    Predict Output

    What does this code print? Think carefully about date arithmetic.

    from datetime import date, timedelta
    d = date(2024, 2, 28)
    result = d + timedelta(days=1)
    print(result)
    Loading editor...
    Sort Events by Date
    Write Code

    Given three date strings in '%Y-%m-%d' format, parse them, sort them from earliest to latest, and print each one formatted as '%B %d, %Y' on its own line.

    Dates: '2024-12-25', '2024-07-04', '2024-10-31'

    Loading editor...