🕒 Python datetime Module – Master Dates & Times in Python | TechTown.in

Working with dates and times is a common need in real-world applications — from setting reminders and logging activity, to timestamping messages and managing bookings.

Python makes this easy with the powerful datetime module.

In this guide, you’ll learn how to create, manipulate, and format dates and times using Python’s datetime module — with simple examples and real-life use cases.


📦 What is the datetime Module?

The datetime module in Python lets you work with date and time objects in a clean and readable way.

✅ To get started:

import datetime

📅 Get the Current Date and Time

import datetime

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

🎯 Output:

2025-06-26 12:30:45.123456

✅ This returns the current local date and time, down to microseconds.


🧱 Breakdown of datetime.now()

AttributeMeaningExample
yearYear2025
monthMonth (1–12)6
dayDay of month26
hour24-hour format12
minuteMinute30
secondSecond45
print(now.year)
print(now.month)
print(now.day)

📅 Create a Custom Date

my_date = datetime.datetime(2023, 12, 31)
print(my_date)

✅ You must specify: year, month, and day. Time is optional (defaults to 00:00:00).


⏰ Format Dates with strftime()

You can convert dates into readable strings using strftime():

now = datetime.datetime.now()
print(now.strftime("%A, %d %B %Y"))

🎯 Output:

Wednesday, 26 June 2025

Popular strftime() format codes:

CodeOutput ExampleDescription
%Y2025Full year
%m06Month (zero-padded)
%d26Day (zero-padded)
%H14Hour (24-hour)
%I02Hour (12-hour)
%pPMAM/PM
%AWednesdayDay name
%BJuneMonth name

🔁 Parse Strings to Dates with strptime()

date_string = "2025-06-26"
dt = datetime.datetime.strptime(date_string, "%Y-%m-%d")
print(dt)

🎯 Output:

2025-06-26 00:00:00

Use this when reading date strings from user input or files.


➕ Date Arithmetic with timedelta

from datetime import timedelta

today = datetime.datetime.now()
tomorrow = today + timedelta(days=1)
print(tomorrow)

✅ You can add or subtract days, hours, minutes, etc.

one_week_later = today + timedelta(weeks=1)
three_hours_ago = today - timedelta(hours=3)

⏱️ Time Only – Use datetime.time

t = datetime.time(9, 45, 0)
print(t)

🎯 Output:

09:45:00

🧪 Real-Life Use Case – Expiry Reminder System

expiry_date = datetime.datetime(2025, 7, 1)
today = datetime.datetime.now()

if expiry_date > today:
    print("✅ Still valid")
else:
    print("⚠️ Expired!")

Use this logic in event scheduling, subscriptions, library systems, etc.


📝 Summary – Python datetime Cheatsheet

TaskCode Example
Current timedatetime.datetime.now()
Custom datedatetime.datetime(2023, 12, 31)
Format as string.strftime("%Y-%m-%d")
Convert string to datestrptime("2025-06-26", "%Y-%m-%d")
Add time+ timedelta(days=2)
Get just timedatetime.time(14, 30)

🏁 Final Thoughts

The datetime module is a must-know if you’re building apps that involve:

  • Deadlines & timers
  • Logging
  • Timestamps in databases
  • Reminders and notifications

With just a few lines of code, Python lets you work with time like a pro.


📘 Continue learning powerful Python modules at TechTown.in