Datetime in Python

Date and Time in Python

Handling date and time in Python is essential for many data-related tasks. Python provides several modules, like datetime, time, and pytz, to make working with date and time easy and flexible.

Here’s an overview of how to handle date and time in Python:

Datetime module

The datetime module provides a range of classes and functions to work with dates, times, and intervals.

Importing datetime

import datetime
  • Getting the current date and time
# Current date and time
now = datetime.datetime.now()
print(now)

# Current date
today = datetime.date.today()
print(today)
  • Creating Date and Time Objects
# Creating a date object
my_date = datetime.date(2025, 2, 9)
print(my_date)

# Creating a time object
my_time = datetime.time(14, 30, 45)  # hours, minutes, seconds
print(my_time)

# Creating a datetime object
my_datetime = datetime.datetime(2025, 2, 9, 14, 30, 45)
print(my_datetime)

Time Operations

The time module allows you to work with time-related tasks such as sleep, execution time, and more.

import time

# Current time in seconds since the epoch
epoch_time = time.time()
print(epoch_time)

# Pausing execution for a given number of seconds
print("Start sleeping")
time.sleep(2)  # Sleep for 2 seconds
print("Wake up")

Working with Time Zones

For working with different time zones, you can use the pytz library.

First, install pytz:

pip install pytz
  • Using Time Zones
import datetime
import pytz

# Get timezone-aware datetime for a specific timezone
utc_now = datetime.datetime.now(pytz.UTC)
print(utc_now)

# Convert UTC time to another timezone (e.g., New York)
ny_tz = pytz.timezone("America/New_York")
ny_time = utc_now.astimezone(ny_tz)
print(ny_time)
  • Localize Datetime
# Localizing a naive datetime (without timezone information)
naive_datetime = datetime.datetime(2025, 2, 9, 14, 30, 45)
localized_datetime = ny_tz.localize(naive_datetime)
print(localized_datetime)

Working with Timedelta

timedelta objects represent differences in time and can be used to add or subtract time.

# Creating a timedelta object
delta = datetime.timedelta(days=5, hours=3, minutes=30)

# Adding timedelta to the current time
new_datetime = now + delta
print(new_datetime)

# Subtracting timedelta from the current time
new_datetime = now - delta
print(new_datetime)
No questions available.