Data & Time
Working with Dates and Times in Python
In Python, the datetime module provides classes for working with dates and times. The datetime module includes several classes, such as datetime, date, time, timedelta, and timezone, among others.
Date and Time Representation:
datetime Class:
from datetime import datetime
# Current date and time
current_datetime = datetime.now()
print("Current Date and Time:", current_datetime)
# Specific date and time
specific_datetime = datetime(2023, 12, 24, 18, 30, 0)
print("Specific Date and Time:", specific_datetime)
date Class:
from datetime import date
# Current date
current_date = date.today()
print("Current Date:", current_date)
# Specific date
specific_date = date(2023, 12, 24)
print("Specific Date:", specific_date)
time Class:
from datetime import time
# Current time
current_time = time.now()
print("Current Time:", current_time)
# Specific time
specific_time = time(18, 30, 0)
print("Specific Time:", specific_time)
Formatting and Parsing Dates:
from datetime import datetime
# Formatting datetime as string
current_datetime = datetime.now()
formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
print("Formatted Datetime:", formatted_datetime)
# Parsing string into datetime
date_string = "2023-12-24 18:30:00"
parsed_datetime = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print("Parsed Datetime:", parsed_datetime)
Timedelta:
from datetime import datetime, timedelta
# Current date and time
current_datetime = datetime.now()
# Calculate future date
future_date = current_datetime + timedelta(days=7)
print("Future Date:", future_date)
# Calculate past date
past_date = current_datetime - timedelta(weeks=2)
print("Past Date:", past_date)
Time Zones:
from datetime import datetime, timezone, timedelta
# UTC time
utc_time = datetime.now(timezone.utc)
print("UTC Time:", utc_time)
# Convert UTC time to a specific time zone
tz = timezone(timedelta(hours=5)) # Example: UTC+5
local_time = utc_time.astimezone(tz)
print("Local Time:", local_time)
These are some of the basics of working with dates and times in Python using the datetime module. The module provides a versatile set of tools for handling a wide range of date and time-related operations.