Introduction
Whether you’re logging events, scheduling tasks, or processing timestamps, working with dates and times is essential in Python. The built-in datetime module provides a powerful set of tools to handle date and time data effectively. This article walks through the basics of using datetime in real-world use cases.
Getting the Current Date and Time
To get the current date and time, use datetime.now():
from datetime import datetime
now = datetime.now()
print("Current datetime:", now)
Formatting Dates and Times
You can format date objects as readable strings using strftime():
print(now.strftime("%Y-%m-%d %H:%M:%S"))
Common format codes include:
%Y: year (e.g. 2025)%m: month (01–12)%d: day%H: hour%M: minute%S: second
Parsing Strings into Dates
Use strptime() to convert strings into datetime objects:
date_str = "2025-07-27"
date_obj = datetime.strptime(date_str, "%Y-%m-%d")
print(date_obj)
Working with timedelta
The timedelta class allows you to do date arithmetic:
from datetime import timedelta
yesterday = now - timedelta(days=1)
next_week = now + timedelta(weeks=1)
print("Yesterday:", yesterday)
print("Next week:", next_week)
Extracting Components
You can access individual components easily:
print(now.year)
print(now.month)
print(now.day)
Conclusion
The datetime module is one of Python’s most useful standard tools for time-based data. Whether you’re logging, scheduling, or calculating time spans, it allows for accurate and flexible date and time manipulation.




Comment