Dates and Times

Working with dates and times is a common requirement in many Python programs. Python provides powerful modules like datetime and time to handle dates, times, and time-related tasks easily.

Why Use Dates and Times?

  • To record or display when something happened.
  • To measure time intervals (e.g., elapsed time).
  • To perform date calculations (e.g., adding days, finding differences).
  • To handle time zones or formats.

The datetime Module

The datetime module is the most commonly used for handling dates and times. It provides the following key classes:

  • datetime: Represents both date and time.
  • date: Represents only a date (year, month, day).
  • time: Represents only time (hours, minutes, seconds).
  • timedelta: Represents the difference between two dates or times.

Getting the Current Date and Time

You can get the current date and time using the now() function from the datetime class.

Example:

Python
Copy
from datetime import datetime

current_time = datetime.now()
print(current_time)  # Output: 2024-11-15 14:30:12.345678

Formatting Dates and Times

You can format dates and times using the strftime() method. It allows you to represent dates in different styles.

Example:

Python
Copy
formatted_date = current_time.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_date)  # Output: 2024-11-15 14:30:12

Common Format Codes:

  • %Y: Year (e.g., 2024)
  • %m: Month (01-12)
  • %d: Day (01-31)
  • %H: Hour (24-hour clock)
  • %M: Minute
  • %S: Second

Parsing Strings into Dates

Use the strptime() method to convert strings into datetime objects.

Example:

Python
Copy
date_string = "2024-11-15"
parsed_date = datetime.strptime(date_string, "%Y-%m-%d")
print(parsed_date)  # Output: 2024-11-15 00:00:00

Working with timedelta

The timedelta class helps you perform date calculations, like adding or subtracting days.

Example:

Python
Copy
from datetime import timedelta

future_date = current_time + timedelta(days=10)
print(future_date)  # Output: 2024-11-25

past_date = current_time - timedelta(days=5)
print(past_date)    # Output: 2024-11-10

Comparing Dates and Times

You can compare datetime objects using comparison operators (<, >, ==, etc.).

Example:

Python
Copy
date1 = datetime(2024, 11, 15)
date2 = datetime(2024, 12, 1)

print(date1 < date2)  # Output: True

The time Module

The time module provides additional functions to work with time, particularly for system-level tasks like measuring elapsed time.

Key Features of time Module

  • time(): Returns the current time in seconds since the epoch (January 1, 1970).
  • sleep(): Pauses program execution for a specific number of seconds.
Example:
Python
Copy
import time

# Measure execution time
start = time.time()
time.sleep(2)  # Pause for 2 seconds
end = time.time()

print(f"Elapsed time: {end - start} seconds")  # Output: Elapsed time: 2.0 seconds

Time Zones and Localization

To handle time zones, use the pytz library (an external module).

Example:

Python
Copy
from datetime import datetime
import pytz

# Set timezone
utc = pytz.UTC
local_time = pytz.timezone("Asia/Kolkata")

# Get current time in UTC
utc_now = datetime.now(utc)
print(utc_now)  # Output: 2024-11-15 09:00:00+00:00

# Convert to local time
local_now = utc_now.astimezone(local_time)
print(local_now)  # Output: 2024-11-15 14:30:00+05:30