Understanding Date and Time in Python
Python provides a built-in module called datetime
that allows you to work with dates, times, and time intervals. This module offers a range of classes and functions to handle various date and time-related operations.
Datetime Class
The datetime
class is the primary class in the datetime
module, and it represents a specific date and time. It has the following attributes:
year
: The year (4-digit integer)
month
: The month (1-12)
day
: The day of the month (1-31)
hour
: The hour (0-23)
minute
: The minute (0-59)
second
: The second (0-59)
microsecond
: The microsecond (0-999999)
You can create a datetime
object using the datetime()
function:
from datetime import datetime
## Create a datetime object
dt = datetime(2023, 5, 1, 12, 30, 0)
print(dt) ## Output: 2023-05-01 12:30:00
The datetime
class also provides methods for formatting and parsing date and time strings. You can use the strftime()
method to format a datetime
object as a string, and the strptime()
method to parse a string into a datetime
object.
## Format a datetime object as a string
print(dt.strftime("%Y-%m-%d %H:%M:%S")) ## Output: 2023-05-01 12:30:00
## Parse a string into a datetime object
date_str = "2023-05-01 12:30:00"
parsed_dt = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
print(parsed_dt) ## Output: 2023-05-01 12:30:00
Timedelta Class
The timedelta
class represents a duration of time, and it can be used to calculate the difference between two datetime
objects. You can create a timedelta
object by specifying the number of days, seconds, and microseconds.
from datetime import datetime, timedelta
## Calculate the difference between two datetime objects
dt1 = datetime(2023, 5, 1, 12, 30, 0)
dt2 = datetime(2023, 5, 5, 15, 45, 0)
diff = dt2 - dt1
print(diff) ## Output: 4 days, 3:15:00
By understanding the basics of the datetime
module in Python, you'll be able to work with dates and times effectively in your applications.