DATETIME MODULE IN PYTHON
Python’s `datetime` module is a powerful tool for working with dates and times in Python. It provides classes to represent dates, times, and timedeltas (differences between dates or times). Here’s an overview of how you can use the `datetime` module:
Importing the `datetime` Module:
“`python
import datetime
“`
Current Date and Time:
“`python
# Get the current date and time
current_datetime = datetime.datetime.now()
print(“Current Date and Time:”, current_datetime)
“`
Date:
“`python
# Get the current date
current_date = datetime.date.today()
print(“Current Date:”, current_date)
“`
Time:
“`python
# Get the current time
current_time = datetime.datetime.now().time()
print(“Current Time:”, current_time)
“`
Creating Datetime Objects:
“`python
# Create a specific datetime object
specific_datetime = datetime.datetime(2022, 2, 24, 12, 30, 0)
print(“Specific Datetime:”, specific_datetime)
“`
Formatting Datetime Objects:
“`python
# Format a datetime object as a string
formatted_datetime = specific_datetime.strftime(“%Y-%m-%d %H:%M:%S”)
print(“Formatted Datetime:”, formatted_datetime)
“`
Parsing Strings into Datetime Objects:
“`python
# Parse a string into a datetime object
parsed_datetime = datetime.datetime.strptime(“2022-02-24 12:30:00”, “%Y-%m-%d %H:%M:%S”)
print(“Parsed Datetime:”, parsed_datetime)
“`
Arithmetic with Datetimes and Timedeltas:
“`python
# Calculate the difference between two datetimes
difference = datetime.datetime(2022, 3, 1) – datetime.datetime(2022, 2, 24)
print(“Difference in Days:”, difference.days)
# Add or subtract a timedelta from a datetime object
new_datetime = datetime.datetime.now() + datetime.timedelta(days=7)
print(“New Datetime (7 days later):”, new_datetime)
“`
The `datetime` module is invaluable for handling various date and time-related operations in Python, making it easier to work with temporal data in your programs.