![]() |
VOOZH | about |
In Python, adding time (such as hours, minutes, seconds, or days) to a datetime object is commonly done using the timedelta class from the datetime module. This allows precise manipulation of date and time values, including performing arithmetic operations on datetime objects. It's key features include:
Example:
Now: 2025-05-24 06:00:32.837564 In 10 days: 2025-06-03 06:00:32.837564
Explanation:
datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
Parameters:
Parameter | Description |
|---|---|
days | Number of days |
seconds | Number of seconds |
microseconds | Number of microseconds |
milliseconds | Number of milliseconds (converted to microseconds) |
minutes | Number of minutes (converted to seconds) |
hours | Number of hours (converted to seconds) |
weeks | Number of weeks (converted to days) |
Returns: This method returns a datetime.timedelta object which represents a duration (not an absolute date). This object can be added to or subtracted from datetime.datetime or datetime.date objects to perform date/time arithmetic.
Example 1: Add 1 day to a datetime object
Original: 2025-05-24 10:00:00 After Adding 1 Day: 2025-05-25 10:00:00
Explanation: datetime(2025, 5, 24, 10, 0, 0) creates a specific datetime object for May 24, 2025, 10:00:00 AM and a + timedelta(days=1) adds 1 day to the datetime a, resulting in b.
Example 2: Add hours and minutes
Updated Datetime: 2025-05-24 16:45:00
Explanation: datetime(2025, 5, 24, 14, 30) creates a specific datetime object for May 24, 2025, 2:30 PM and a + timedelta(hours=2, minutes=15) adds 2 hours and 15 minutes to the datetime a, resulting in b.
Example 3: Subtract Hours from a Datetime
New Datetime: 2025-05-24 09:00:00
Explanation: datetime(2025, 5, 24, 12, 0) creates a specific datetime object for May 24, 2025, 12:00 PM and a - timedelta(hours=3) subtracts 3 hours from the datetime a, resulting in b.
Example 4: Add weeks, days and hours
Final Datetime: 2025-06-02 14:00:00
Explanation: datetime(2025, 5, 24, 9, 0) creates a datetime object for May 24, 2025, 9:00 AM and a + timedelta(weeks=1, days=2, hours=5) adds 1 week, 2 days and 5 hours to a, resulting in b.