🔍 Introduction
Working with date and time is essential in most real-world applications, such as logging events, scheduling tasks, or building time-based functionality. Python’s built-in datetime
module provides a robust set of functions to handle dates and times effortlessly.
🎯 Objective
The objective of this tutorial is to demonstrate how to:
- Get the current date and time
- Format dates and times
- Calculate time differences
- Work with timedeltas (date/time arithmetic)
💻 Python Code Example
import datetime
# Get current date and time
now = datetime.datetime.now()
print(“Current Date and Time:”, now)
# Format date
formatted_date = now.strftime(“%A, %d %B %Y %I:%M:%S %p”)
print(“Formatted Date:”, formatted_date)
# Create a specific date
custom_date = datetime.datetime(2024, 12, 25, 10, 30)
print(“Custom Date:”, custom_date)
# Time difference between now and custom date
time_diff = custom_date – now
print(“Time until Custom Date:”, time_diff)
# Add 7 days to current date
week_later = now + datetime.timedelta(days=7)
print(“Date One Week from Now:”, week_later)
🧠 Explanation of the Program
Here’s how the program works:
- datetime.datetime.now() fetches the current local date and time.
- strftime() formats the datetime object into a readable string.
- datetime.datetime() creates a custom date object (like a future event).
- Subtracting two
datetime
objects gives atimedelta
, which shows the time difference. - datetime.timedelta(days=7) is used to add (or subtract) days from a date.
🚀 How to Run the Program
- Make sure you have Python installed (version 3.6+ is recommended).
- Open your favorite text editor or IDE (such as VS Code, PyCharm, or even Notepad).
- Copy and paste the code into a new file and save it as
datetime_demo.py
. - Open a terminal or command prompt, navigate to the file location, and run:
python datetime_demo.py