4 Python Datetime
1. What is Datetime in Python?
Datetime is used to work with date and time in Python.
In simple words:
👉 Datetime helps us know
-
Today’s date
-
Current time
-
Year, month, day, hour, minute
Python provides a built-in module called datetime.
2. Import Datetime Module
Example
3. Get Current Date and Time
Example
Output (example):
4. Get Only Date
Example
Output:
5. Get Only Time
Example
6. Access Year, Month, Day
Example
7. Create Your Own Date
Example
8. Create Your Own Time
Example
9. Create Your Own Datetime
Example
10. Format Date and Time (strftime)
strftime() is used to change date format.
Example
Common Format Codes
| Code | Meaning |
|---|---|
| %d | Day |
| %m | Month |
| %Y | Year |
| %H | Hour |
| %M | Minute |
| %S | Second |
11. Convert String to Date (strptime)
Example
12. Date Difference (Timedelta)
timedelta is used to add or subtract days.
Example
13. Compare Dates
Example
14. Common Beginner Mistakes
❌ Forgetting Module Name
❌ Error.
✔ Correct:
❌ Wrong Date Format
❌ Invalid month.
15. Simple Practice Examples
Example 1: Print Today’s Year
Example 2: Add 10 Days
Example 3: Custom Date Format
16. Summary (Python Datetime)
✔ Used to work with date and time
✔ datetime.now() gives current date & time
✔ strftime() formats date
✔ timedelta adds or subtracts days
✔ Very useful in real programs
📘 Perfect for Beginner eBook
This chapter is ideal for:
-
Python beginner books
-
School & college students
-
Self-learners
If you want next, I can write:
-
Python Math Module
-
Python JSON
-
File Handling
-
Exception Handling
-
Mini Python Projects
Just tell me 😊
