The datetime module in Python provides classes for working with dates and times. It's an essential tool for handling temporal data in your programs.
To use the datetime module, you need to import it first:
from datetime import datetime, date, time, timedelta
You can create date and time objects using the datetime class:
# Current date and time
now = datetime.now()
# Specific date and time
custom_date = datetime(2023, 5, 15, 14, 30, 0)
The datetime module allows you to format dates and times as strings:
# Format as string
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_date) # Output: 2023-05-15 14:30:00
You can convert string representations of dates and times back into datetime objects:
date_string = "2023-05-15 14:30:00"
parsed_date = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
The timedelta class allows you to perform date arithmetic:
# Add 7 days to the current date
future_date = now + timedelta(days=7)
# Calculate the difference between two dates
diff = future_date - now
print(diff.days) # Output: 7
To further enhance your datetime skills, explore these related topics:
Mastering the datetime module is crucial for handling time-sensitive operations in Python. It's widely used in various applications, from scheduling tasks to data analysis and web development.