Python Time Handling: datetime, time, and pytz Modules Tutorial
This article introduces Python's datetime, time, and pytz modules, demonstrating how to obtain the current date and time, format and parse strings, compute time differences, work with timestamps, perform sleep operations, and handle time zones with clear code examples.
Python frequently requires handling dates and times, and the built-in datetime and time modules together with the third‑party pytz library cover most common tasks.
1. datetime module
The datetime module provides classes such as datetime , date , time and timedelta for date‑time manipulation.
Get the current date and time:
from datetime import datetime
now = datetime.now()
print(f"Current date and time: {now}")Get the current date only:
from datetime import date
today = date.today()
print(f"Current date: {today}")Get the current time only:
from datetime import datetime, time
now = datetime.now()
current_time = now.time()
print(f"Current time: {current_time}")Format a datetime object as a string:
from datetime import datetime
now = datetime.now()
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(f"Formatted date and time: {formatted_date}")Parse a datetime string:
from datetime import datetime
date_str = "2023-10-01 12:34:56"
parsed_date = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
print(f"Parsed date and time: {parsed_date}")Calculate time differences using timedelta :
from datetime import datetime, timedelta
now = datetime.now()
future = now + timedelta(days=7, hours=2, minutes=30)
print(f"Future time: {future}")
time_diff = future - now
print(f"Time difference: {time_diff}")
print(f"Time difference in seconds: {time_diff.total_seconds()} seconds")Replace specific parts of a datetime:
from datetime import datetime
now = datetime.now()
new_datetime = now.replace(year=2024, month=12, day=31, hour=23, minute=59, second=59)
print(f"Replaced datetime: {new_datetime}")2. time module
The time module offers functions for timestamps and sleeping.
Get the current timestamp:
import time
current_timestamp = time.time()
print(f"Current timestamp: {current_timestamp}")Convert a timestamp to a formatted date‑time string (using both time and datetime ):
import time
from datetime import datetime
current_timestamp = time.time()
local_time = time.localtime(current_timestamp)
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", local_time)
print(f"Formatted time (time module): {formatted_time}")
# Using datetime
formatted_time = datetime.fromtimestamp(current_timestamp).strftime("%Y-%m-%d %H:%M:%S")
print(f"Formatted time (datetime): {formatted_time}")Sleep for a specified number of seconds:
import time
print("Starting sleep...")
time.sleep(5) # sleep for 5 seconds
print("Sleep finished")3. pytz module
The pytz library adds time‑zone support.
Get the current UTC time and convert it to Shanghai time:
from datetime import datetime
import pytz
utc_now = datetime.now(pytz.utc)
print(f"UTC time: {utc_now}")
shanghai_tz = pytz.timezone('Asia/Shanghai')
shanghai_now = utc_now.astimezone(shanghai_tz)
print(f"Shanghai time: {shanghai_now}")Parse a datetime string with a specific time zone and convert it to UTC:
from datetime import datetime
import pytz
date_str = "2023-10-01 12:34:56"
shanghai_tz = pytz.timezone('Asia/Shanghai')
local_time = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
local_time = shanghai_tz.localize(local_time)
utc_time = local_time.astimezone(pytz.utc)
print(f"Localized time: {local_time}")
print(f"Converted UTC time: {utc_time}")Summary
The datetime module provides comprehensive date and time handling, the time module offers timestamp and sleep utilities, and the pytz library enables robust time‑zone operations, all illustrated with practical code examples.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.