Tutorials Logic, IN info@tutorialslogic.com

Dates in Python datetime, strftime, timedelta

Python Dates

Python date and time code uses objects such as date, time, datetime, and timedelta instead of plain strings.

Use date objects for calendar days, datetime objects for exact moments, and timedelta objects for durations.

The safest date workflow is parse text once, calculate with date objects, then format text only when showing output.

datetime Module

Python's built-in datetime module provides classes for working with dates and times. The main classes are date, time, datetime, and timedelta.

Current Date and Time

Current Date & Time

Current Date & Time
from datetime import date, time, datetime

# Current date
today = date.today()
print(today)           # 2024-01-15
print(today.year)      # 2024
print(today.month)     # 1
print(today.day)       # 15

# Current date and time
now = datetime.now()
print(now)             # 2024-01-15 14:30:45.123456
print(now.hour)        # 14
print(now.minute)      # 30
print(now.second)      # 45

# UTC time
from datetime import timezone
utc_now = datetime.now(timezone.utc)
print(utc_now)

Date and Time Objects

Creating Objects

Creating Objects
from datetime import date, time, datetime

# Specific date
birthday = date(1990, 6, 15)
print(birthday)         # 1990-06-15

# Specific time
alarm = time(7, 30, 0)
print(alarm)            # 07:30:00

# Specific datetime
event = datetime(2024, 12, 25, 18, 0, 0)
print(event)            # 2024-12-25 18:00:00

# From timestamp (Unix time)
import time as t
ts = datetime.fromtimestamp(t.time())
print(ts)

# From ISO format string
dt = datetime.fromisoformat("2024-06-15T14:30:00")
print(dt)

Format Dates

Use strftime() to format a datetime as a string.

strftime - Format Codes

strftime - Format Codes
from datetime import datetime

now = datetime(2024, 6, 15, 14, 30, 45)

print(now.strftime("%Y-%m-%d"))           # 2024-06-15
print(now.strftime("%d/%m/%Y"))           # 15/06/2024
print(now.strftime("%B %d, %Y"))          # June 15, 2024
print(now.strftime("%A, %B %d, %Y"))      # Saturday, June 15, 2024
print(now.strftime("%I:%M %p"))           # 02:30 PM
print(now.strftime("%H:%M:%S"))           # 14:30:45
print(now.strftime("%Y-%m-%dT%H:%M:%S"))  # ISO 8601

# Common format codes:
# %Y = 4-digit year    %m = month (01-12)   %d = day (01-31)
# %H = hour (00-23)    %M = minute (00-59)  %S = second (00-59)
# %I = hour (01-12)    %p = AM/PM           %A = weekday name
# %B = month name      %j = day of year     %W = week number

Parse Dates

strptime - Parse Strings

strptime - Parse Strings
from datetime import datetime

# Parse a date string into a datetime object
dt = datetime.strptime("2024-06-15", "%Y-%m-%d")
print(dt)           # 2024-06-15 00:00:00

dt2 = datetime.strptime("June 15, 2024 2:30 PM", "%B %d, %Y %I:%M %p")
print(dt2)          # 2024-06-15 14:30:00

# Convert between formats
user_input = "15/06/2024"
parsed = datetime.strptime(user_input, "%d/%m/%Y")
formatted = parsed.strftime("%B %d, %Y")
print(formatted)    # June 15, 2024

Date Arithmetic

timedelta

timedelta
from datetime import date, datetime, timedelta

today = date.today()

# Add/subtract days
tomorrow = today + timedelta(days=1)
last_week = today - timedelta(weeks=1)
next_month = today + timedelta(days=30)

print(tomorrow)     # tomorrow's date
print(last_week)    # 7 days ago
print(next_month)   # 30 days from now

# Difference between two dates
start = date(2024, 1, 1)
end = date(2024, 12, 31)
diff = end - start
print(diff.days)    # 365

# Age calculator
birthday = date(1990, 6, 15)
today = date.today()
age = today.year - birthday.year
if (today.month, today.day) < (birthday.month, birthday.day):
    age -= 1
print(f"Age: {age}")

# Time difference
start_time = datetime(2024, 1, 1, 9, 0, 0)
end_time = datetime(2024, 1, 1, 17, 30, 0)
duration = end_time - start_time
print(duration)              # 8:30:00
print(duration.seconds)      # 30600 seconds
print(duration.seconds // 3600)  # 8 hours
Date handling check

Can You Work With Date and Time Values?

5 checks
  • Use date for calendar days and datetime for exact moments.
  • Use timedelta for adding or subtracting durations.
  • Parse date strings once before doing date calculations.
  • Format dates only when showing output to users.
  • Use timezone-aware datetimes for real-world timestamps.

Date and Time Traps

  • Treating formatted text as a date

    Parse text into a date or datetime object before doing date calculations.
  • Ignoring time zones in real apps

    Use timezone-aware datetimes when comparing events across regions or systems.
  • Using the wrong format code

    Check strftime and strptime codes carefully; %m is month and %M is minute.

Try this next

Format a Real Date

0 of 3 completed

  1. Print today in YYYY-MM-DD format.
  2. Convert a date string into a date object and print the year.
  3. Use timedelta to find the date seven days from today.

Questions About Date

Store and calculate with date or datetime objects. Format as strings only when displaying or exporting.

timedelta represents a duration, such as 7 days or 3 hours, and is used for date arithmetic.

A time without timezone information can mean different moments in different places. Use aware datetimes for real-world timestamps.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.