Handling temporal data is crucial in nearly every application, from simple logging to time-based analytics, scheduling systems, and time zone conversions. Date and Time Manipulation in Python allows developers to format, calculate, compare, and localize date and time information using standard and third-party libraries.
Python provides both built-in and third-party libraries for effective date and time operations. The most commonly used libraries include:
from datetime import datetime, date, time # Get current date and time now = datetime.now() print("Current datetime:", now) # Create a specific date custom_date = date(2024, 12, 25) print("Custom date:", custom_date)
You can convert datetime objects to strings and vice versa using strftime() and strptime().
from datetime import datetime # Format datetime to string dt = datetime(2024, 6, 13, 14, 30) formatted = dt.strftime("%Y-%m-%d %H:%M:%S") print("Formatted:", formatted) # Parse string to datetime parsed = datetime.strptime("2024-06-13 14:30:00", "%Y-%m-%d %H:%M:%S") print("Parsed:", parsed)
The timedelta class is used for arithmetic operations between dates and times.
from datetime import timedelta now = datetime.now() future = now + timedelta(days=10, hours=5) difference = future - now print("Future:", future) print("Difference:", difference)
from datetime import datetime import pytz utc = pytz.utc local = pytz.timezone("Asia/Kolkata") # Current UTC time utc_now = datetime.now(utc) # Convert to local time local_time = utc_now.astimezone(local) print("UTC Time:", utc_now) print("Local Time:", local_time)
Region | Timezone |
---|---|
India | Asia/Kolkata |
US Eastern | US/Eastern |
UTC | UTC |
Japan | Asia/Tokyo |
import time start = time.time() # Simulate delay time.sleep(2) end = time.time() print("Execution time:", end - start, "seconds")
dateutil.parser allows parsing of almost any human-readable date string without needing a format specifier.
from dateutil import parser dt = parser.parse("June 13, 2025 03:45PM") print("Parsed:", dt)
You can use rrule from dateutil.rrule for recurring events:
from dateutil.rrule import rrule, DAILY from datetime import datetime start = datetime(2025, 6, 13) for dt in rrule(DAILY, count=5, dtstart=start): print(dt)
Directive | Meaning | Example |
---|---|---|
%Y | Year with century | 2025 |
%m | Month (01–12) | 06 |
%d | Day of month | 13 |
%H | Hour (00–23) | 15 |
%M | Minute | 45 |
%S | Second | 30 |
Date and Time Manipulation in Python is a critical skill for developers working on real-time applications, logging systems, time-based analytics, and scheduling tools. Python’s rich set of modules, including datetime, pytz, and dateutil, offer precise and reliable capabilities for all time-based tasks. Understanding how to parse, format, compare, and convert time makes your applications robust and time-aware.
Copyrights © 2024 letsupdateskills All rights reserved