Python Datetime Module Basics
Working with dates and times is one of the most important tasks in programming. Python provides a powerful and flexible module called datetime to handle this. It lets you easily manage dates, times, time intervals, and formatting.
If you've ever wondered how to get today's date in Python, calculate the difference between two dates, or convert a string into a date object, this guide has you covered with ready-to-use code examples.
What is the datetime Module?
The datetime module is part of Python's standard library. It provides classes for manipulating dates and times. Since it's built-in, no extra 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
- Handle time zones
Import the module 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. Use the today() method from the date class:
from datetime import date
today = date.today()
print(f"Today's date: {today}")
The output is in YYYY-MM-DD format, for example: 2025-05-09.
Getting the Current Date and Time Together
If you need 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 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"Hour: {current_time.hour}")
print(f"Minute: {current_time.minute}")
print(f"Second: {current_time.second}")
Formatting Dates and Times
Formatting Basics
You often need to display a date in a human-readable format. Use the strftime() method to specify your desired format:
now = datetime.now()
formatted = now.strftime("%d-%m-%Y %H:%M:%S")
print(f"Formatted date and time: {formatted}")
Common Format Codes
The datetime module supports many format codes:
- %Y — Year (4 digits), e.g., 2025
- %m — Month (zero-padded), e.g., 05
- %d — Day of the month, e.g., 09
- %H — Hour (24-hour clock), e.g., 14
- %M — Minute, e.g., 30
- %S — Second, e.g., 45
- %A — Full weekday name, e.g., Friday
- %B — Full month name, e.g., 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 strptime():
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}")
Date Arithmetic
Calculating the Difference Between Dates
The datetime module makes it easy to calculate the number of days between two dates. The result is a timedelta object:
from datetime import date
date1 = date(2025,