Introduction
Mastering the intricacies of date and time in Python is pivotal for applications dealing with scheduling, events, or any temporal aspects. This documentation provides insights into fundamental concepts and practical techniques for handling dates and times.
1. The 'datetime' Module Basics
1.1. Importing the 'datetime' Module
The 'datetime' module is your temporal toolkit in Python. Start by importing it along with its related entities.
from datetime import datetime, date, time
current_datetime = datetime.now()
print("Current Date and Time:", current_datetime)
# Extracting year, month, and day from current_datetime
year = current_datetime.year month = current_datetime.month day = current_datetime.day
# Displaying the extracted components print("Year :", year, "Month :", month, "Day :", day)
# Formatting and displaying the current date and time
formatted_date = current_datetime.strftime("%A, %B %d, %Y %I:%M %p")
print("Formatted Date:", formatted_date)
# Calculating the date a month from now
from datetime import timedelta
next_month = current_datetime + timedelta(days=30) print("Date a month from now:", next_month)
# Creating a specific time
from datetime import time
specific_time = time(18, 45, 0) print("Specific Time:", specific_time)
# Creating a specific datetimefrom datetime import datetime, date, time
specific_datetime = datetime.combine(date(2023, 8, 15), time(12, 0, 0)) print("Specific DateTime:", specific_datetime)
Conclusion
Navigating the temporal dimensions in Python empowers you to orchestrate events, schedules, and more. Embrace the capabilities of the `datetime` module, adapt these examples to your unique scenarios, and elevate your Python applications that traverse the realms of time.