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

import datetime

now = datetime.datetime.now()
print(now)

Example output:

2025-12-03 10:45:32.567890

🗓 2. Get Current Date Only

today = datetime.date.today()
print(today)

Output:

2025-12-03

🕰 3. Get Current Time Only

now = datetime.datetime.now()
print(now.time())

🎯 4. Creating a Custom Date or Time

# Create a date
d = datetime.date(2025, 12, 25)
print(d)
# Create a time
t = datetime.time(10, 30, 45)
print(t)

# Create full datetime
dt = datetime.datetime(2025, 12, 25, 10, 30, 45)
print(dt)


🔍 5. Extract Parts of Date

now = datetime.datetime.now()

print(now.year)
print(now.month)
print(now.day)
print(now.hour)
print(now.minute)
print(now.second)


🧮 6. Date Arithmetic (Add/Subtract)

from datetime import datetime, timedelta

today = datetime.now()

# Add 5 days
future = today + timedelta(days=5)

# Subtract 10 days
past = today – timedelta(days=10)

print(future)
print(past)


🎉 7. Calculate Age or Days Difference

from datetime import date

birthdate = date(2000, 5, 10)
today = date.today()

age_days = today – birthdate
print(“Days lived:”, age_days.days)

age_years = age_days.days // 365
print(“Age:”, age_years)


🔤 8. Formatting Dates (strftime)

strftime() converts date to a readable string format.

now = datetime.datetime.now()

formatted = now.strftime(“%d-%m-%Y %H:%M:%S”)
print(formatted)

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:

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

🔁 9. Converting String → Date (strptime)

from datetime import datetime

date_string = “03-12-2025”
converted = datetime.strptime(date_string, “%d-%m-%Y”)

print(converted)


⏱ 10. Working with UNIX Timestamp

import datetime

now = datetime.datetime.now()

# Convert to timestamp
timestamp = now.timestamp()
print(timestamp)

# Convert timestamp back
dt_from_ts = datetime.datetime.fromtimestamp(timestamp)
print(dt_from_ts)


🌎 11. Datetime with Timezone

from datetime import datetime
import pytz
timezone = pytz.timezone(“Asia/Kolkata”)
dt = datetime.now(timezone)

print(dt)

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

  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”).

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *