Python datetime: Working with Dates and Time

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

The datetime module in Python provides powerful tools for working with dates and time. This library is essential for generating reports, analytics, scheduling events, and handling timestamps in any software project.

Getting Started with the datetime Module

Importing and Core Classes

The datetime module is part of Python's standard library and requires no additional installation:

import datetime
from datetime import date, time, datetime, timedelta, timezone

Core classes of the module:

  • datetime.date — work with dates (year, month, day)
  • datetime.time — work with time (hours, minutes, seconds)
  • datetime.datetime — combines date and time
  • datetime.timedelta — represents the difference between dates/times
  • datetime.timezone — work with time zones

Getting the Current Date and Time

from datetime import datetime, date

# Current date and time
now = datetime.now()
print(f"Current date and time: {now}")

# Current date only
today = date.today()
print(f"Today's date: {today}")

Creating and Working with Dates

Creating Dates Manually

from datetime import date, datetime

# Create a specific date
custom_date = date(2025, 5, 9)
print(f"Custom date: {custom_date}")

# Create a date and time
custom_datetime = datetime(2025, 5, 9, 14, 30, 45)
print(f"Custom date and time: {custom_datetime}")

Extracting Date Components

today = date.today()
print(f"Year: {today.year}")
print(f"Month: {today.month}")
print(f"Day: {today.day}")
print(f"Weekday: {today.weekday()}")  # 0 = Monday, 6 = Sunday

Working with Time

Creating and Using Time Objects

from datetime import time

# Create a time object
custom_time = time(14, 30, 45)
print(f"Custom time: {custom_time}")

# Extract time components
print(f"Hours: {custom_time.hour}")
print(f"Minutes: {custom_time.minute}")
print(f"Seconds: {custom_time.second}")

Getting Time with Microseconds

from datetime import datetime

now = datetime.now()
print(f"Time with microseconds: {now}")
print(f"Microseconds: {now.microsecond}")

Date Arithmetic

Using timedelta

from datetime import date, datetime, timedelta

# Date operations
today = date.today()
tomorrow = today + timedelta(days=1)
last_week = today - timedelta(weeks=1)
next_month = today + timedelta(days=30)

print(f"Tomorrow: {tomorrow}")
print(f"Last week: {last_week}")
print(f"Next month: {next_month}")

# More complex operations
future_date = today + timedelta(days=100, hours=5, minutes=30)
print(f"In 100 days, 5 hours, and 30 minutes: {future_date}")

Calculating the Difference Between Dates

from datetime import date, datetime

start_date = date(2025, 1, 1)
end_date = date(2025, 12, 31)

# Difference in days
difference = end_date - start_date
print(f"Difference in days: {difference.days}")

# Difference in seconds for datetime
start_time = datetime(2025, 5, 9, 10, 0, 0)
end_time = datetime(2025, 5, 9, 15, 30, 45)

time_diff = end_time - start_time
print(f"Difference in seconds: {time_diff.total_seconds()}")
print(f"Difference in hours: {time_diff.total_seconds() / 3600}")

Formatting Dates and Time

The strftime Method

from datetime import datetime

now = datetime.now()

# Various formats
print(now.strftime("%Y-%m-%d"))  # 2025-05-09
print(now.strftime("%B %d, %Y"))  # May 09, 2025
print(now.strftime("%I:%M %p"))  # 02:30 PM
print(now.strftime("%A, %B %d, %Y at %I:%M %p"))  # Friday, May 09, 2025 at 02:30 PM

Parsing Strings into Dates with strptime

from datetime import datetime

# Parse a date string
date_string = "2025-05-09 14:30:45"
parsed_date = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print(f"Parsed date: {parsed_date}")

# Parse other formats
date_string2 = "May 9, 2025"
parsed_date2 = datetime.strptime(date_string2, "%B %d, %Y")
print(f"Parsed date 2: {parsed_date2}")

Working with Time Zones

Using timezone Objects

from datetime import datetime, timezone, timedelta

# UTC time
utc_time = datetime.now(timezone.utc)
print(f"UTC time: {utc_time}")

# Create a custom timezone (UTC+3)
custom_tz = timezone(timedelta(hours=3))
custom_time = datetime.now(custom_tz)
print(f"UTC+3 time: {custom_time}")

# Convert between timezones
from_tz = timezone(timedelta(hours=-5))
to_tz = timezone(timedelta(hours=3))

time_in_ny = datetime.now(from_tz)
time_in_moscow = time_in_ny.astimezone(to_tz)
print(f"New York time: {time_in_ny}")
print(f"Moscow time: {time_in_moscow}")

Working with pytz (Third-Party Library)

# Install: pip install pytz
from datetime import datetime
import pytz

# Get timezone objects
tz_moscow = pytz.timezone('Europe/Moscow')
tz_ny = pytz.timezone('America/New_York')
tz_tokyo = pytz.timezone('Asia/Tokyo')

# Current time in different timezones
moscow_time = datetime.now(tz_moscow)
ny_time = datetime.now(tz_ny)
tokyo_time = datetime.now(tz_tokyo)

print(f"Moscow: {moscow_time}")
print(f"New York: {ny_time}")
print(f"Tokyo: {tokyo_time}")

# Convert between timezones
utc_time = datetime.now(pytz.utc)
moscow_time = utc_time.astimezone(tz_moscow)
print(f"UTC to Moscow: {moscow_time}")

Practical Examples

Calculating Age

from datetime import date

def calculate_age(birth_date):
    today = date.today()
    age = today.year - birth_date.year
    
    # Check if birthday has passed this year
    if (today.month, today.day) < (birth_date.month, birth_date.day):
        age -= 1
    
    return age

# Example
birthday = date(1990, 5, 15)
age = calculate_age(birthday)
print(f"Age: {age} years")

Date Validation

from datetime import datetime

def validate_date(date_string, format="%Y-%m-%d"):
    try:
        datetime.strptime(date_string, format)
        return True
    except ValueError:
        return False

# Examples
print(validate_date("2025-05-09"))  # True
print(validate_date("2025-13-01"))  # False (invalid month)
print(validate_date("05/09/2025", "%m/%d/%Y"))  # True

Working with Unix Timestamps

from datetime import datetime
import time

# Current Unix timestamp
timestamp = time.time()
print(f"Current Unix timestamp: {timestamp}")

# Convert timestamp to datetime
dt = datetime.fromtimestamp(timestamp)
print(f"Datetime from timestamp: {dt}")

# Convert datetime to timestamp
now = datetime.now()
timestamp_back = now.timestamp()
print(f"Timestamp from datetime: {timestamp_back}")

Best Practices and Tips

  • Always use timezone-aware objects for applications that work across different time zones
  • Store dates in UTC in databases and convert to local time only for display
  • Use timedelta for date arithmetic instead of manually adding days
  • Validate user input dates with strptime to avoid errors
  • Consider using third-party libraries like dateutil or arrow for complex date parsing

Conclusion

The datetime module is a fundamental tool for any Python developer. Mastering it allows you to efficiently handle dates and time in your applications, from simple date formatting to complex time zone conversions. Practice with the examples above and integrate them into your projects to become proficient in Python date and time manipulation.

Blogs

Book Recommendations