Skip to main content
Editor

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
from datetime import date, time, datetime
# Create a specific date: year, month, day
birthday = date(2000, 5, 15)
print(f'Birthday: {birthday}')
# Create a specific time: hour, minute, second
alarm = time(7, 30, 0)
print(f'Alarm: {alarm}')
# Create a full datetime: year, month, day, hour, minute, second
launch = datetime(2024, 3, 14, 9, 30, 0)
print(f'Launch: {launch}')
Output
Birthday: 2000-05-15
Alarm: 07:30:00
Launch: 2024-03-14 09:30:00

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

Accessing date components
from datetime import datetime
event = datetime(2024, 12, 25, 18, 30, 0)
print(f'Year: {event.year}')
print(f'Month: {event.month}')
print(f'Day: {event.day}')
print(f'Hour: {event.hour}')
print(f'Minute: {event.minute}')
print(f'Weekday: {event.strftime("%A")}') # Day of the week
Output
Year: 2024
Month: 12
Day: 25
Hour: 18
Minute: 30
Weekday: Wednesday

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
from datetime import date, datetime
# Current date (no time)
today = date.today()
print(f'Today: {today}')
print(f'Year: {today.year}, Month: {today.month}, Day: {today.day}')
# Current date and time
now = datetime.now()
print(f'Now: {now}')
print(f'Time: {now.hour}:{now.minute:02d}:{now.second:02d}')
Output
Today: 2026-10-20
Year: 2026, Month: 10, Day: 20
Now: 2026-10-20 11:58:38.352999
Time: 11:58:38

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
from datetime import date, timedelta
today = date(2024, 6, 15)
# Add days
next_week = today + timedelta(days=7)
print(f'Today: {today}')
print(f'Next week: {next_week}')
# Subtract days
last_month = today - timedelta(days=30)
print(f'30 days ago: {last_month}')
# Use weeks
two_weeks = today + timedelta(weeks=2)
print(f'Two weeks later: {two_weeks}')
Output
Today: 2024-06-15
Next week: 2024-06-22
30 days ago: 2024-05-16
Two weeks later: 2024-06-29

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
from datetime import date
new_year = date(2025, 1, 1)
christmas = date(2024, 12, 25)
difference = new_year - christmas
print(f'Days between: {difference.days}')
print(f'Type: {type(difference)}')
# How many days in a year?
start = date(2024, 1, 1)
end = date(2024, 12, 31)
print(f'Days in 2024: {(end - start).days + 1}')
Output
Days between: 7
Type: <class 'datetime.timedelta'>
Days in 2024: 366
Working with hours and minutes
from datetime import datetime, timedelta
# timedelta works with hours, minutes, and seconds too
now = datetime(2024, 6, 15, 14, 30, 0)
later = now + timedelta(hours=3, minutes=45)
print(f'Now: {now}')
print(f'3h 45m later: {later}')
# Complex timedelta
future = now + timedelta(days=2, hours=5, minutes=30)
print(f'2 days 5h 30m later: {future}')
Output
Now: 2024-06-15 14:30:00
3h 45m later: 2024-06-15 18:15:00
2 days 5h 30m later: 2024-06-17 20:00:00

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
from datetime import datetime
dt = datetime(2024, 3, 14, 15, 9, 26)
# Common formats
print(dt.strftime('%B %d, %Y')) # March 14, 2024
print(dt.strftime('%m/%d/%Y')) # 03/14/2024
print(dt.strftime('%d-%m-%Y')) # 14-03-2024
print(dt.strftime('%Y-%m-%d %H:%M:%S')) # 2024-03-14 15:09:26
print(dt.strftime('%A, %B %d')) # Thursday, March 14
print(dt.strftime('%I:%M %p')) # 03:09 PM
Output
March 14, 2024
03/14/2024
14-03-2024
2024-03-14 15:09:26
Thursday, March 14
03:09 PM

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
    from datetime import datetime
    # Parse different date formats
    date1 = datetime.strptime('2024-03-14', '%Y-%m-%d')
    print(f'Parsed: {date1}')
    date2 = datetime.strptime('March 14, 2024', '%B %d, %Y')
    print(f'Parsed: {date2}')
    date3 = datetime.strptime('14/03/2024 15:30', '%d/%m/%Y %H:%M')
    print(f'Parsed: {date3}')
    # Once parsed, you can do math with it
    from datetime import timedelta
    next_day = date1 + timedelta(days=1)
    print(f'Next day: {next_day.strftime("%B %d, %Y")}')
    Output
    Parsed: 2024-03-14 00:00:00
    Parsed: 2024-03-14 00:00:00
    Parsed: 2024-03-14 15:30:00
    Next day: March 15, 2024
    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
    from datetime import date
    new_year = date(2025, 1, 1)
    christmas = date(2024, 12, 25)
    halloween = date(2024, 10, 31)
    print(f'Christmas < New Year: {christmas < new_year}')
    print(f'Halloween < Christmas: {halloween < christmas}')
    print(f'New Year == Jan 1: {new_year == date(2025, 1, 1)}')
    # Sort a list of dates
    dates = [new_year, halloween, christmas]
    dates.sort()
    print(f'Sorted: {dates}')
    Output
    Christmas < New Year: True
    Halloween < Christmas: True
    New Year == Jan 1: True
    Sorted: [datetime.date(2024, 10, 31), datetime.date(2024, 12, 25), datetime.date(2025, 1, 1)]
    Checking past vs future dates
    from datetime import date
    # Check if a date is in the past or future
    target = date(2024, 7, 4)
    reference = date(2024, 6, 15)
    if target > reference:
    days_until = (target - reference).days
    print(f'{target} is {days_until} days after {reference}')
    else:
    days_since = (reference - target).days
    print(f'{target} was {days_since} days before {reference}')
    Output
    2024-07-04 is 19 days after 2024-06-15

    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.

    from datetime import date
    # Create July 4, 2024 and print formatted
    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.

    from datetime import date
    # Calculate days between Jan 1 and March 15, 2024
    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).

    from datetime import date, timedelta
    start = date(2024, 6, 15)
    # Add 14 days and print
    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.

    from datetime import datetime
    date_string = '15-06-2024'
    # Parse and reformat
    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)
    from datetime import date, timedelta
    d = date(2024, 2, 28)
    result = d + timedelta(days=1)
    print(result)
    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'

    from datetime import datetime
    date_strings = ['2024-12-25', '2024-07-04', '2024-10-31']
    # Parse, sort, and print formatted

    Harder problems

    More problems on this topic: Parsing

    Related Tutorials

    Was this tutorial helpful?