The Python standard library offers robust support for handling dates, times, and time intervals through two primary modules: datetime and time. These modules provide essential functionality for dealing with real-world problems involving scheduling, logging, time measurement, delays, and more. In this document, we will explore extensive code examples for both modules, demonstrating their individual capabilities as well as their interoperability in various contexts.
import datetime
import time
The datetime module includes classes like datetime, date, time, timedelta, and timezone. The time module provides low-level functions to interact with the system time, sleep, and measure durations.
from datetime import datetime
current_time = datetime.now()
print("Current date and time:", current_time)
custom_dt = datetime(2024, 12, 25, 10, 30, 45)
print("Custom datetime:", custom_dt)
print("Year:", custom_dt.year)
print("Month:", custom_dt.month)
print("Day:", custom_dt.day)
print("Hour:", custom_dt.hour)
print("Minute:", custom_dt.minute)
print("Second:", custom_dt.second)
formatted = current_time.strftime('%Y-%m-%d %H:%M:%S')
print("Formatted datetime:", formatted)
dt_str = '2025-06-27 15:45:00'
parsed_dt = datetime.strptime(dt_str, '%Y-%m-%d %H:%M:%S')
print("Parsed datetime:", parsed_dt)
dt1 = datetime(2025, 6, 27)
dt2 = datetime(2025, 6, 30)
print("Is dt1 before dt2?", dt1 < dt2)
from datetime import timedelta
now = datetime.now()
future = now + timedelta(days=10)
past = now - timedelta(days=5)
print("10 days in the future:", future)
print("5 days in the past:", past)
start_date = datetime(2025, 6, 1)
end_date = datetime(2025, 6, 27)
diff = end_date - start_date
print("Days difference:", diff.days)
replaced = current_time.replace(hour=20, minute=0)
print("Replaced datetime:", replaced)
print("Weekday (0=Monday):", current_time.weekday())
print("ISO Weekday (1=Monday):", current_time.isoweekday())
print("ISO Calendar:", current_time.isocalendar())
print("ISO Format:", current_time.isoformat())
from datetime import date
today = date.today()
print("Today:", today)
specific_date = date(2023, 5, 15)
print("Specific Date:", specific_date)
print("Is today > specific_date?", today > specific_date)
print("Minimum date:", date.min)
print("Maximum date:", date.max)
from datetime import time
t = time(14, 30, 45)
print("Time:", t)
print("Hour:", t.hour)
print("Minute:", t.minute)
print("Second:", t.second)
print("Microsecond:", t.microsecond)
epoch_time = time.time()
print("Time since epoch:", epoch_time)
local_time = time.localtime(epoch_time)
print("Local time struct:", local_time)
print("Readable format:", time.asctime(local_time))
formatted_time = time.strftime('%Y-%m-%d %H:%M:%S', local_time)
print("Formatted:", formatted_time)
print("Sleeping for 2 seconds...")
time.sleep(2)
print("Awake now.")
start = time.perf_counter()
for _ in range(1000000):
pass
end = time.perf_counter()
print("Time taken:", end - start)
from datetime import timezone, timedelta
utc_dt = datetime.now(timezone.utc)
print("UTC Time:", utc_dt)
ist = timezone(timedelta(hours=5, minutes=30))
ist_time = utc_dt.astimezone(ist)
print("IST Time:", ist_time)
import pytz
utc = pytz.utc
india = pytz.timezone("Asia/Kolkata")
now_utc = datetime.now(utc)
now_india = now_utc.astimezone(india)
print("UTC Time:", now_utc)
print("India Time:", now_india)
future_event = datetime(2025, 12, 31, 23, 59, 59)
now = datetime.now()
remaining = future_event - now
print("Time left:", remaining)
dob = date(1990, 7, 1)
today = date.today()
age = today.year - dob.year - ((today.month, today.day) < (dob.month, dob.day))
print("Age:", age)
def log_event(message):
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print(f"[{timestamp}] {message}")
log_event("Program started")
time.sleep(1)
log_event("Operation completed")
def business_days(start_date, end_date):
day_count = 0
while start_date <= end_date:
if start_date.weekday() < 5:
day_count += 1
start_date += timedelta(days=1)
return day_count
start = date(2025, 6, 1)
end = date(2025, 6, 30)
print("Business days:", business_days(start, end))
def scheduler():
print("Task will run in 5 seconds...")
time.sleep(5)
print("Task executed at:", datetime.now())
scheduler()
utc_now = datetime.utcnow()
print("UTC now:", utc_now)
local_dt = utc_now.replace(tzinfo=timezone.utc).astimezone()
print("Local time:", local_dt)
start = date(2025, 1, 1)
date_list = [start + timedelta(days=i) for i in range(10)]
for d in date_list:
print(d)
The Python datetime and time modules offer versatile tools to handle nearly every time-related programming need. From simple tasks like delays and timestamp logging to complex date arithmetic and timezone-aware datetime manipulation, these libraries cover a broad spectrum. This tutorial presented comprehensive, real-world working code examples to help you understand and apply both modules effectively in your projects.
Mastering these modules is particularly useful in domains such as data science (timestamps in data), backend development (logging and session expiration), DevOps (scheduling), and more. You can now confidently format, calculate, convert, and control time in Python applications of all sizes.
Python is commonly used for developing websites and software, task automation, data analysis, and data visualisation. Since it's relatively easy to learn, Python has been adopted by many non-programmers, such as accountants and scientists, for a variety of everyday tasks, like organising finances.
Learning Curve: Python is generally considered easier to learn for beginners due to its simplicity, while Java is more complex but provides a deeper understanding of how programming works.
The point is that Java is more complicated to learn than Python. It doesn't matter the order. You will have to do some things in Java that you don't in Python. The general programming skills you learn from using either language will transfer to another.
Read on for tips on how to maximize your learning. In general, it takes around two to six months to learn the fundamentals of Python. But you can learn enough to write your first short program in a matter of minutes. Developing mastery of Python's vast array of libraries can take months or years.
6 Top Tips for Learning Python
The following is a step-by-step guide for beginners interested in learning Python using Windows.
Best YouTube Channels to Learn Python
Write your first Python programStart by writing a simple Python program, such as a classic "Hello, World!" script. This process will help you understand the syntax and structure of Python code.
The average salary for Python Developer is βΉ5,55,000 per year in the India. The average additional cash compensation for a Python Developer is within a range from βΉ3,000 - βΉ1,20,000.
Copyrights © 2024 letsupdateskills All rights reserved