In Python, the datetime module provides classes for working with dates and times. It allows you to manipulate dates, times, and time intervals, perform arithmetic operations, format dates for display, and much more. Here's an overview of the datetime module:
To use the functionalities provided by the datetime module, you need to import it:
import datetime
The datetime module provides several classes for representing dates and times:
You can create datetime, date, and time objects using their constructors:
Creating a datetime object for the current date and time
now = datetime.datetime.now()
Creating a date object
today = datetime.date.today()
Creating a time object
current_time = datetime.time(10, 30, 0) # Hour, minute, second
You can format dates and times into strings using the strftime() method, which stands for string format time:
formatted_date = now.strftime("%Y-%m-%d")
formatted_time = now.strftime("%H:%M:%S")
print("Formatted date:", formatted_date)
print("Formatted time:", formatted_time)
You can parse strings into datetime, date, and time objects using the strptime() method:
date_string = "2023-05-15"
parsed_date = datetime.datetime.strptime(date_string, "%Y-%m-%d")
print("Parsed date:", parsed_date)
You can perform arithmetic operations on datetime objects using the timedelta class:
Adding or subtracting a duration to/from a datetime object
next_week = now + datetime.timedelta(days=7)
Calculating the difference between two datetime objects
time_difference = next_week - now
print("Time difference:", time_difference)
The datetime module does not provide native support for timezones. For timezone handling, you can use the `pytz` module or the timezone class from the datetime module in Python 3.9 and later.
import datetime
from datetime import timezone
Creating a datetime object with timezone information
dt = datetime.datetime(2023, 5, 15, 12, 0, 0, tzinfo=timezone.utc)
Converting to a different timezone
dt_local = dt.astimezone(timezone.utc)
print("Local time:", dt_local)
The datetime module is a powerful tool for working with dates and times in Python. It provides a wide range of functionalities for manipulating and formatting date and time data, making it easier to work with temporal information in your Python programs.