How do I use the datetime module to work with dates?

онлайн тренажер по питону
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

Python Datetime Module Fundamentals: A Comprehensive Guide

Working with dates and times is a crucial task in programming. In Python, the powerful and flexible datetime module is used for this purpose. This module allows you to conveniently manage dates, times, time intervals, and formatting.

If you've ever wondered how to get today's date in Python, how to calculate the difference between dates, or how to convert a string to a date, this article will provide you with comprehensive answers and ready-to-use code examples.

What is the Datetime Module?

The datetime module is part of the Python standard library. It provides classes for managing time and dates. This module is built-in, so no additional installation is required.

With the datetime module, you can:

  • Get the current date and time
  • Perform arithmetic operations on dates
  • Format and convert dates
  • Work with time intervals using the timedelta class
  • Manage time zones

The module is imported in the standard way:

import datetime

Getting the Current Date and Time

How to Get Today's Date

Getting the current date is one of the most common tasks. The today() method from the date class is used for this:

from datetime import date
today = date.today()
print(f"Today's date: {today}")

The result is displayed in the format YYYY-MM-DD, for example: 2025-05-09.

Getting the Current Time and Date Simultaneously

If you need to get both the date and time, use the datetime class and the now() method:

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

Extracting Individual Date and Time Components

The datetime module makes it easy to extract individual date and time components:

current_time = datetime.now()
print(f"Year: {current_time.year}")
print(f"Month: {current_time.month}")
print(f"Day: {current_time.day}")
print(f"Hours: {current_time.hour}")
print(f"Minutes: {current_time.minute}")
print(f"Seconds: {current_time.second}")

Formatting Date and Time

Formatting Basics

Often, it is necessary to present the date in a human-readable format. The strftime() method is used for this, which allows you to specify the desired display format:

now = datetime.now()
formatted = now.strftime("%d-%m-%Y %H:%M:%S")
print(f"Formatted date and time: {formatted}")

Popular Formatting Codes

The datetime module supports many formatting codes:

  • %Y — Year (4 digits), for example: 2025
  • %m — Month (with leading zero), for example: 05
  • %d — Day of the month, for example: 09
  • %H — Hours (24-hour format), for example: 14
  • %M — Minutes, for example: 30
  • %S — Seconds, for example: 45
  • %A — Full name of the day of the week, for example: Friday
  • %B — Full name of the month, for example: May

Converting a String to a Date

If you have a date as a string and need to convert it to a datetime object, use the strptime() method:

from datetime import datetime
date_string = "09-05-2025"
converted_date = datetime.strptime(date_string, "%d-%m-%Y")
print(f"Date after conversion: {converted_date}")

Arithmetic Operations on Dates

Calculating the Difference Between Dates

The datetime module makes it easy to calculate the number of days between two dates. The result is represented by a timedelta object:

from datetime import date
date1 = date(2025, 5, 9)
date2 = date(2025, 12, 31)
delta = date2 - date1
print(f"Days left until New Year: {delta.days}")

Working with Time Intervals

The timedelta class is designed for working with time intervals. It allows you to add or subtract a certain number of days, hours, or minutes:

from datetime import datetime, timedelta
now = datetime.now()
future = now + timedelta(days=10)
print(f"Date in 10 days: {future}")

You can use various units of time:

  • days — days
  • seconds — seconds
  • microseconds — microseconds
  • milliseconds — milliseconds
  • minutes — minutes
  • hours — hours
  • weeks — weeks

Additional Features of the Datetime Module

Determining the Day of the Week

The datetime module makes it easy to determine the day of the week for any date:

date_example = datetime(2025, 5, 9)
day_of_week = date_example.strftime("%A")
print(f"Day of the week: {day_of_week}")

Working with Time Zones

Starting with Python 3.2, the datetime module supports working with time zones through the timezone class:

from datetime import datetime, timezone
utc_time = datetime.now(timezone.utc)
print(f"Current UTC time: {utc_time}")

Practical Examples and Frequently Asked Questions

Getting Only the Current Time

from datetime import datetime
current_time = datetime.now().time()
print(f"Current time: {current_time}")

Checking for a Leap Year

import calendar
print(calendar.isleap(2024))  # True, since 2024 is a leap year

Rounding Time to the Nearest Hour

now = datetime.now().replace(minute=0, second=0, microsecond=0)
print(f"Rounded time: {now}")

Calculating the Time Difference in Minutes

from datetime import datetime
time1 = datetime(2025, 5, 9, 12, 0)
time2 = datetime(2025, 5, 9, 14, 30)
delta = time2 - time1
print(f"Difference in minutes: {delta.total_seconds() / 60}")

Getting Yesterday's Date

from datetime import datetime, timedelta
yesterday = datetime.now() - timedelta(days=1)
print(f"Yesterday's date: {yesterday.date()}")

Working with Time Zones via pytz

For more flexible work with time zones, it is recommended to use the third-party pytz library:

pip install pytz
from datetime import datetime
import pytz
timezone = pytz.timezone("Europe/Moscow")
moscow_time = datetime.now(timezone)
print(f"Current time in Moscow: {moscow_time}")

Practical Applications of the Datetime Module

Creating Logs with Timestamps

from datetime import datetime

def log_message(message):
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    print(f"[{timestamp}] {message}")

log_message("System started")

Calculating Age

from datetime import date

def calculate_age(birth_date):
    today = date.today()
    age = today.year - birth_date.year
    if today < birth_date.replace(year=today.year):
        age -= 1
    return age

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

Determining Working Days

from datetime import datetime, timedelta

def get_working_days(start_date, end_date):
    working_days = 0
    current_date = start_date
    
    while current_date <= end_date:
        if current_date.weekday() < 5:  # 0-4 это понедельник-пятница
            working_days += 1
        current_date += timedelta(days=1)
    
    return working_days

start = datetime(2025, 5, 1)
end = datetime(2025, 5, 31)
working_days = get_working_days(start, end)
print(f"Working days in May: {working_days}")

Conclusion

The datetime module is a powerful tool for working with dates and times in Python. It provides everything you need to effectively manage time data.

You can easily get today's date, calculate the difference between dates, format time to your requirements, and even work with time zones. The datetime module supports a wide range of operations: from simply getting the current date to complex calculations of time intervals.

If you plan to professionally engage in data analysis, web development, or process automation, knowledge of this module will definitely come in handy. Mastering the work with datetime will open up many opportunities for creating more functional and practical programs.

News