If you write code for a living, sooner or later you’ll need to work with dates and times. That’s where the Python datetime module comes in.
It powers everything from timestamping logs to scheduling emails, to calculating payroll dates. It’s one of those modules you might overlook when starting out, but as your projects grow, you realize just how critical it is.
This guide explains datetime Python in plain language. You’ll see how to get today’s date and time, format it, work with timezones, and avoid common mistakes developers make. Along the way, we’ll also explore real-world use cases that you can directly apply in your job.
🔑 Key Highlights
- Learn what the datetime module in Python is and why it matters
- Get today’s date and time in Python with
datetime.now() - Extract year, month, day, hour, minute, second, and microsecond easily
- Work with timezones using
pytzand the modernzoneinfomodule - See real-world use cases (logging, scheduling, APIs) and best practices
- FAQs: converting strings ↔ datetime, formatting dates, comparing dates

What is the datetime Module in Python?
Every developer asks at some point: “Which module in Python can be used to work with dates and times?”
The answer is simple: the datetime module.
It provides classes to handle:
- Dates (
date) - Times (
time) - Both together (
datetime) - Time differences (
timedelta)
Here’s the simplest example of getting today’s date and time with Python datetime:
from datetime import datetime current_dateTime = datetime.now() print(current_dateTime) # Example: 2025-09-04 18:12:45.123456
How to Import datetime in Python
A lot of beginners confuse import datetime vs from datetime import datetime. Here’s the difference:
import datetime→ you’ll need to calldatetime.datetime.now().from datetime import datetime→ you can directly usedatetime.now().
Best practice? Use the second one. It’s cleaner and less repetitive.
How to Use datetime.now() to Get Today’s Date and Time
The most common method in the Python datetime module is now(). It gives you the exact date and time when your code runs.
from datetime import datetime
now = datetime.now()
print("Current Date & Time:", now)
In real-world apps, developers use this to:
- Add timestamps to log files 📝
- Record transaction times in e-commerce apps 🛒
- Track API request times for debugging
datetime.now() Attributes in Python
Sometimes you don’t need the full timestamp — just a piece of it. The datetime Python object provides easy attributes:
from datetime import datetime
now = datetime.now()
print("Year:", now.year)
print("Month:", now.month)
print("Day:", now.day)
print("Hour:", now.hour)
print("Minute:", now.minute)
print("Second:", now.second)
print("Microsecond:", now.microsecond)
👉 This granularity is crucial in production. Imagine a finance app calculating interest rates — you’d better have the exact second when the transaction was logged.
How to Convert String to datetime in Python (Parsing)
You’ll often get dates as strings (like "2025-09-04") from users or APIs. You can’t compare them directly — you need to parse them into a datetime object.
That’s where strptime() comes in:
from datetime import datetime date_str = "2025-09-04 18:45:00" dt_object = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S") print(dt_object)
Why is this useful?
- Reading user input in forms 📅
- Parsing timestamps from CSV logs
- Processing dates from external APIs
How to Convert datetime to String in Python (Formatting)
The opposite problem also comes up: you need to show a datetime in a human-friendly way. That’s where strftime() helps.
from datetime import datetime
now = datetime.now()
print(now.strftime("%d-%b-%Y %H:%M"))
# Example: 04-Sep-2025 18:45
This is critical for reporting dashboards, invoices, and anywhere user-facing.
How to Work with Timezones in Python
Timezones are where many developers trip up. What looks fine in development suddenly fails when users are spread across continents.
Using pytz (Legacy but Popular)
from datetime import datetime
import pytz
lagos_time = datetime.now(pytz.timezone('Africa/Lagos'))
print(lagos_time)
Using zoneinfo (Modern – Python 3.9+)
Python 3.9 introduced zoneinfo, built-in and recommended.
from datetime import datetime
from zoneinfo import ZoneInfo
tokyo_time = datetime.now(ZoneInfo("Asia/Tokyo"))
print(tokyo_time)
📌 Pro tip: Always store times in UTC in your database, then convert to local timezone for display. This prevents bugs when daylight savings changes.

Real-World Use Cases of Python datetime
Here are situations where datetime Python is non-negotiable:
- Logging systems → attach timestamps for every event
- Finance apps → calculate interest rates or deadlines
- Scheduling apps → book meetings across different timezones
- Data pipelines → filter records between two dates
- APIs → return standardized ISO 8601 timestamps
Fun fact: according to Stack Overflow’s Developer Survey 2024, 55% of Python developers say they frequently work with dates and times in projects.
Best Practices for Using Python datetime
- ✅ Always use timezone-aware datetime objects for production systems
- ✅ Use
strftimeandstrptimefor formatting and parsing - ✅ Store timestamps in UTC in databases
- ✅ Avoid naive datetime (those without timezone info) unless you’re absolutely sure you don’t need it
- ✅ Use timedelta for calculations (e.g., add 7 days)
FAQs About Python datetime
Q1: What is the datetime module in Python?
It’s a standard library that handles dates, times, and intervals.
Q2: How to get only today’s date in Python?
print(datetime.now().date())
Q3: How to get only the time in Python?
print(datetime.now().time())
Q4: How to compare two dates in Python?
Convert both to datetime objects and use comparison operators (>, <, ==).
Q5: How to calculate difference between two dates?
Use timedelta:
d1 = datetime(2025, 9, 1) d2 = datetime(2025, 9, 4) print((d2 - d1).days) # 3
Summary
The Python datetime module isn’t flashy, but it’s one of the most important tools in a developer’s toolbox. It helps you handle today’s date, current time, string conversions, timezones, and date arithmetic with precision.
Whether you’re building a finance app, a data pipeline, or just automating reports, understanding datetime Python will save you from countless headaches.
👉 Keep it simple, stay consistent, and always test with different timezones. Your future self — and your users — will thank you.
🔗 Related reads:
- Python Official datetime Docs
- Python strftime() and strptime() Format Codes
- Python Course – Comprehensive Python training program covering core modules including datetime.
- Top 15 Key Features of Python in 2025 – Blog post highlighting Python’s strengths and modern features.
- Python Tutorial – Beginner-friendly tutorial series on Python basics and beyond.
- Array in Python – Introduction & Functions – Covers arrays in Python with functions and examples.
- Master Python’s Datetime Module – Hands-on video guide to working with Python’s datetime module.