About Lesson
Pandas provides several powerful functions for manipulating date and time data. This section will cover various operations such as extracting components of dates, performing arithmetic, and working with time zones.
a. Extracting Components of Date/Time
You can extract various components like year, month, day, hour, minute, etc., from a Timestamp
or DatetimeIndex
object.
# Extract components from a Timestamp
timestamp = pd.to_datetime('2024-11-30 14:30:00')
print("Year:", timestamp.year)
print("Month:", timestamp.month)
print("Day:", timestamp.day)
print("Hour:", timestamp.hour)
print("Minute:", timestamp.minute)
print("Second:", timestamp.second)
Output:
Year: 2024
Month: 11
Day: 30
Hour: 14
Minute: 30
Second: 0
b. Date Arithmetic
Pandas allows you to perform arithmetic operations on dates, such as adding or subtracting days, months, and years.
# Adding days to a Timestamp
new_timestamp = timestamp + pd.Timedelta(days=5)
print(f"New Timestamp after adding 5 days: {new_timestamp}")
# Subtracting days from a Timestamp
earlier_timestamp = timestamp - pd.Timedelta(days=10)
print(f"Timestamp 10 days earlier: {earlier_timestamp}")
Output:
New Timestamp after adding 5 days: 2024-12-05 14:30:00
Timestamp 10 days earlier: 2024-11-20 14:30:00
c. Working with DateOffsets
Pandas also allows you to work with DateOffset
objects for more complex date manipulation, such as adding months or business days.
# Add 3 months to a date
timestamp_with_months = timestamp + pd.DateOffset(months=3)
print(f"Timestamp after adding 3 months: {timestamp_with_months}")
# Add 2 business days
business_days_added = timestamp + pd.offsets.BDay(2)
print(f"Timestamp after adding 2 business days: {business_days_added}")
Output:
Timestamp after adding 3 months: 2025-02-28 14:30:00
Timestamp after adding 2 business days: 2024-12-02 14:30:00