Date manipulation in Python

Manipulate Date and Time in Python

Date manipulation in Python is a crucial skill, and the datetime module provides a comprehensive set of tools to work with date and time. Here's a detailed guide to date manipulation:

Date Arithmetic

You can perform arithmetic operations (addition or subtraction) on dates and times using timedelta.

  • Adding/Subtracting Days to/from a Date
# Adding days to current date
future_date = today + datetime.timedelta(days=10)
print(future_date)  # Output: 2025-02-19

# Subtracting days from current date
past_date = today - datetime.timedelta(days=5)
print(past_date)  # Output: 2025-02-04
  • Adding/Subtracting Hours, Minutes, or Seconds
# Adding hours to current time
new_time = now + datetime.timedelta(hours=5)
print(new_time)  # Output: 2025-02-09 19:30:45

# Subtracting minutes from current time
new_time_sub = now - datetime.timedelta(minutes=30)
print(new_time_sub)  # Output: 2025-02-09 14:00:45
  • Time Difference Between Two Dates

You can subtract two datetime objects to get a timedelta object, which represents the difference.

# Date difference between two datetime objects
start = datetime.datetime(2025, 2, 1)
end = datetime.datetime(2025, 2, 9)
difference = end - start
print(difference)  # Output: 8 days, 0:00:00

# Get number of days
print(difference.days)  # Output: 8

Formatting Dates

You can convert datetime objects into readable strings using strftime().

# Format current datetime
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_date)  # Output: 2025-02-09 14:30:45

# Custom format for weekday and month
formatted_custom = now.strftime("%A, %B %d, %Y")
print(formatted_custom)  # Output: Sunday, February 09, 2025

The format codes include:

  • %Y: Year with century (e.g., 2025)
  • %m: Month as a two-digit number (e.g., 02)
  • %d: Day of the month as a two-digit number (e.g., 09)
  • %H: Hour (00-23)
  • %M: Minute (00-59)
  • %S: Second (00-59)
  • %A: Full weekday name (e.g., Monday)
  • %B: Full month name (e.g., February)

Parsing Date Strings

You can convert a string into a datetime object using strptime().

# Convert string to datetime
date_str = "2025-02-09 14:30:45"
parsed_date = datetime.datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
print(parsed_date)  # Output: 2025-02-09 14:30:45

Handling Weekdays and Weekends

You can get the day of the week and perform checks.

# Get weekday (0: Monday, 6: Sunday)
weekday = now.weekday()
print(weekday)  # Output: 6 (Sunday)

# Check if today is weekend
if now.weekday() >= 5:  # 5 and 6 correspond to Saturday and Sunday
    print("It's the weekend!")

Comparing Dates

You can compare dates to check if one is earlier, later, or equal to another.

# Comparison of dates
date1 = datetime.date(2025, 2, 9)
date2 = datetime.date(2025, 2, 10)

# Check if date1 is earlier than date2
if date1 < date2:
    print(f"{date1} is earlier than {date2}")

# Check if dates are equal
if date1 == date2:
    print("Both dates are the same")
else:
    print(f"{date1} is not equal to {date2}")

Date Ranges

You can create a range of dates using timedelta and loop through it.

# Create a date range using timedelta
start_date = datetime.date(2025, 2, 1)
end_date = datetime.date(2025, 2, 9)

delta = datetime.timedelta(days=1)
current_date = start_date

while current_date <= end_date:
    print(current_date)
    current_date += delta

Adding Business Days

You can use numpy or pandas for adding business days to a date.

pip install numpy
import numpy as np

# Add business days to a date
start_date = np.datetime64('2025-02-09')
new_date = np.busday_add(start_date, 5)  # Adds 5 business days
print(new_date)  # Output: 2025-02-14

Converting Between Different Time Formats

  • Converting Between Strings and Date Objects:
date_str = "2025-02-09"
date_obj = datetime.datetime.strptime(date_str, "%Y-%m-%d").date()
print(date_obj)  # Output: 2025-02-09
No questions available.