🔷 Introduction
Handling dates and time is essential in many real-world applications such as scheduling systems, logs, data analysis, and APIs.
Python provides a powerful built-in module called datetime to work with dates and time efficiently.
In this lesson, you will learn:
✔ How to create and manipulate dates
✔ How to format and parse date strings
✔ How to perform time calculations
✔ How to work with durations using timedelta
🟩 1. The datetime Module
🔹 Importing
from datetime import datetime🔹 Get current date and time
now = datetime.now()
print(now)🔹 Get only the date
print(now.date())🔹 Get only the time
print(now.time())🟩 2. Creating Custom Dates
from datetime import datetime
d = datetime(2025, 1, 15, 10, 30)
print(d)✔ Format: datetime(year, month, day, hour, minute)
🟩 3. Formatting Dates (strftime)
Convert date → string:
now = datetime.now()
print(now.strftime("%Y-%m-%d"))
print(now.strftime("%d/%m/%Y"))
print(now.strftime("%H:%M:%S"))🔹 Common format codes
| Code | Meaning |
|---|---|
| %Y | Year |
| %m | Month |
| %d | Day |
| %H | Hour |
| %M | Minute |
| %S | Second |
🟩 4. Parsing Dates (strptime)
Convert string → date:
from datetime import datetime
date_str = "2025-01-15"
date_obj = datetime.strptime(date_str, "%Y-%m-%d")
print(date_obj)🟩 5. Time Calculations (timedelta)
🔹 Adding time
from datetime import timedelta
now = datetime.now()
future = now + timedelta(days=7)
print(future)🔹 Subtracting dates
past = datetime(2024, 1, 1)
diff = now - past
print(diff.days)🟩 6. Practical Examples
🔹 Calculate age
birth = datetime(2000, 5, 10)
today = datetime.now()
age = today.year - birth.year
print("Age:", age)🔹 Check if a date is in the future
event = datetime(2025, 12, 31)
if event > datetime.now():
print("Event is upcoming")🟧 7. Exercises (Hidden Solutions)
Exercise 1 — Print current date
Exercise 2 — Format today’s date
Exercise 3 — Parse a date string
Exercise 4 — Add 10 days to today
Exercise 5 — Calculate difference between two dates
🟦 Conclusion
In this lesson, you learned how to:
✔ Work with dates and time using datetime
✔ Format and parse date strings
✔ Perform time calculations
✔ Handle real-world date scenarios
These skills are widely used in:
- APIs
- Data analysis
- Logging systems
- Scheduling applications
🚀 Mini Project — Event Scheduler & Countdown App
Project idea
Build a Python program that lets the user:
- enter an event name
- enter an event date
- calculate how many days remain until the event
- show whether the event is in the future, today, or already passed
This project is perfect for practicing:
datetimestrptime()strftime()- date comparison
timedelta
🧩 What the app does
Example:
Enter event name: Python Exam
Enter event date (YYYY-MM-DD): 2026-12-20Output:
Event: Python Exam
Date: 20/12/2026
Days remaining: 45If the date is today:
The event is today!If the date is in the past:
This event has already passed.✅ Full Solution
🧠 Skills practiced
With this mini project, you practice:
- parsing dates with
strptime() - formatting dates with
strftime() - comparing dates
- using
timedeltaindirectly through date subtraction - handling invalid input with
try/except
🛠 Improved Version — Multiple Events
Here is a slightly more advanced version that stores several events in a list.
🎯 Challenge ideas
You can extend the project with:
- sort events by nearest date
- save events to a file
- show only future events
- add event time
- create a GUI version with Tkinter
- highlight the nearest upcoming event
💬 Comments
No comments yet. Be the first to comment!
Login to comment.