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

import datetime

📅 1. Get Current Date and Time


 

Example output:

2025-12-03 10:45:32.567890

🗓 2. Get Current Date Only



 

Output:

2025-12-03

🕰 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:

CodeMeaningExample
%dDay03
%mMonth12
%YYear (full)2025
%yYear (short)25
%HHour (24 hr)21
%IHour (12 hr)09
%MMinutes55
%SSeconds30
%AFull weekdayWednesday
%BFull monthDecember

Example:

print(now.strftime("Today is %A, %d %B %Y"))

🔁 9. Converting String → Date (strptime)


 


⏱ 10. Working with UNIX Timestamp


 


🌎 11. Datetime with Timezone


 

(Requires installing pytz: pip install pytz)


🧠 Summary

OperationMethod
Get current datetimedatetime.now()
Only datedate.today()
Convert to stringstrftime()
Convert from stringstrptime()
Add/subtract daystimedelta()
Timestamp.timestamp() / fromtimestamp()

📝 Practice Exercises

Try these:

  1. Print current date in format: DD/MM/YYYY.

  2. Calculate how many days are left for New Year.

  3. Ask the user for birthdate and calculate exact age in years.

  4. Convert "2025-05-01 15:30" to Python datetime.

  5. Print today’s weekday name (e.g., “Wednesday”).

You may also like...