Python datetime Module
🕒 Python datetime Module
The datetime module in Python helps you work with:
✔ Dates
✔ Time
✔ Timestamps
✔ Formatting
✔ Date calculations (age, duration, difference, etc.)
📌 Importing datetime
📅 1. Get Current Date and Time
Example output:
🗓 2. Get Current Date Only
Output:
🕰 3. Get Current Time Only
🎯 4. Creating a Custom Date or Time
🔍 5. Extract Parts of Date
🧮 6. Date Arithmetic (Add/Subtract)
🎉 7. Calculate Age or Days Difference
🔤 8. Formatting Dates (strftime)
strftime() converts date to a readable string format.
Common strftime Format Codes:
| Code | Meaning | Example |
|---|---|---|
%d |
Day | 03 |
%m |
Month | 12 |
%Y |
Year (full) | 2025 |
%y |
Year (short) | 25 |
%H |
Hour (24 hr) | 21 |
%I |
Hour (12 hr) | 09 |
%M |
Minutes | 55 |
%S |
Seconds | 30 |
%A |
Full weekday | Wednesday |
%B |
Full month | December |
Example:
🔁 9. Converting String → Date (strptime)
⏱ 10. Working with UNIX Timestamp
🌎 11. Datetime with Timezone
(Requires installing pytz: pip install pytz)
🧠 Summary
| Operation | Method |
|---|---|
| Get current datetime | datetime.now() |
| Only date | date.today() |
| Convert to string | strftime() |
| Convert from string | strptime() |
| Add/subtract days | timedelta() |
| Timestamp | .timestamp() / fromtimestamp() |
📝 Practice Exercises
Try these:
-
Print current date in format:
DD/MM/YYYY. -
Calculate how many days are left for New Year.
-
Ask the user for birthdate and calculate exact age in years.
-
Convert
"2025-05-01 15:30"to Python datetime. -
Print today’s weekday name (e.g., “Wednesday”).
