Python provides powerful modules to work with dates and times. The datetime module and time module allow developers to handle, manipulate, format, and compute date and time efficiently. These modules are widely used in automation, logging, scheduling, and data analysis.
The datetime module is part of Python's standard library and is used for manipulating date and time objects. It provides classes such as date, time, datetime, and timedelta.
The time module is used for time-related operations such as fetching the current time, pausing program execution, and performing epoch-related calculations. It is closer to the system clock and focuses more on performance and lower-level operations.
The Python datetime module provides various classes for working with dates and times in a clean and object-oriented way. Understanding its classes is crucial for effective time management in Python programs.
import datetime
from datetime import date, time, datetime, timedelta
The date class is used to create date objects and perform operations like comparison, formatting, and arithmetic with dates.
# Creating a date object
today = date.today()
print("Today's date:", today)
# Extracting year, month, and day
print("Year:", today.year)
print("Month:", today.month)
print("Day:", today.day)
# Creating a specific date
birthday = date(1990, 5, 15)
print("Birthday:", birthday)
The time class allows you to work with hours, minutes, seconds, and microseconds independently of dates.
# Creating a time object
meeting_time = time(14, 30, 45) # 2:30:45 PM
print("Meeting Time:", meeting_time)
# Accessing hour, minute, second
print("Hour:", meeting_time.hour)
print("Minute:", meeting_time.minute)
print("Second:", meeting_time.second)
The datetime class combines date and time. It is highly versatile and can be used for timestamping and datetime arithmetic.
# Creating a datetime object
now = datetime.now()
print("Current Date and Time:", now)
# Accessing individual components
print("Year:", now.year)
print("Month:", now.month)
print("Day:", now.day)
print("Hour:", now.hour)
print("Minute:", now.minute)
print("Second:", now.second)
# Creating a specific datetime
event = datetime(2026, 1, 15, 18, 45, 0)
print("Event Date and Time:", event)
Python's strftime() method is used to format date and time objects into readable strings. strptime() is used to parse strings into datetime objects.
# Formatting datetime
current_time = datetime.now()
formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S")
print("Formatted DateTime:", formatted_time)
# Parsing string to datetime
date_str = "2026-01-15 10:30:00"
parsed_date = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
print("Parsed DateTime:", parsed_date)
The timedelta class allows you to perform arithmetic operations like addition or subtraction on dates and times.
# Adding 10 days to current date
future_date = today + timedelta(days=10)
print("Date after 10 days:", future_date)
# Subtracting 2 hours from current datetime
past_time = now - timedelta(hours=2)
print("Time 2 hours ago:", past_time)
# Difference between two dates
difference = future_date - today
print("Difference:", difference.days, "days")
The Python time module provides functions related to time manipulation and conversion, often used for measuring performance, pausing execution, and converting between different time formats.
import time
You can fetch the current time in seconds since the Epoch (January 1, 1970) or as a readable string.
# Time in seconds since Epoch
epoch_time = time.time()
print("Epoch Time:", epoch_time)
# Convert epoch to local time
local_time = time.localtime(epoch_time)
print("Local Time:", local_time)
# Human-readable format
readable_time = time.asctime(local_time)
print("Readable Time:", readable_time)
The sleep() function is used to pause program execution for a specified number of seconds.
print("Start")
time.sleep(5) # Pauses for 5 seconds
print("End after 5 seconds")
The strftime() and strptime() methods in the time module are similar to those in datetime for converting time objects to strings and vice versa.
# Formatting time
current_time = time.localtime()
formatted_time = time.strftime("%H:%M:%S %d-%m-%Y", current_time)
print("Formatted Time:", formatted_time)
# Parsing string to time struct
time_string = "15:30:00 15-01-2026"
parsed_time = time.strptime(time_string, "%H:%M:%S %d-%m-%Y")
print("Parsed Time Struct:", parsed_time)
The time module is commonly used for benchmarking code execution.
start = time.time()
# Some heavy computation
sum_val = 0
for i in range(1, 1000000):
sum_val += i
end = time.time()
print("Time taken for computation:", end - start, "seconds")
The time module allows conversions between seconds, local time, and UTC time.
# Convert epoch to UTC
utc_time = time.gmtime(epoch_time)
print("UTC Time:", utc_time)
# Convert struct_time back to epoch
epoch_again = time.mktime(local_time)
print("Epoch Again:", epoch_again)
| Feature | DateTime Module | Time Module |
|---|---|---|
| Level | High-level, object-oriented | Low-level, closer to system time |
| Main Classes | date, time, datetime, timedelta, tzinfo | Functions only (struct_time) |
| Time Arithmetic | Supports timedelta for easy arithmetic | Manual calculations using seconds since epoch |
| Formatting | strftime, strptime | strftime, strptime (struct_time) |
| Use Case | Applications needing high-level date/time manipulation | Applications requiring low-level performance or system time access |
import time
from datetime import datetime, timedelta
# Task scheduled after 10 seconds
print("Task will run after 10 seconds")
time.sleep(10)
print("Task executed at", datetime.now())
from datetime import date
birth_date = date(1990, 5, 15)
today = date.today()
age = today.year - birth_date.year - ((today.month, today.day) < (birth_date.month, birth_date.day))
print("Age:", age)
from datetime import datetime
def log_message(message):
print(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - {message}")
log_message("Application started")
log_message("Task completed")
Pythonβs datetime and time modules provide robust capabilities to work with date and time. The datetime module is ideal for high-level, object-oriented date-time operations, whereas the time module is suited for performance measurement, sleep operations, and system-time access. Mastering these modules is essential for Python developers to handle scheduling, logging, time calculation, and data processing efficiently.
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