Python DateTime - Timedelta Class

Python DateTime - Timedelta Class

The timedelta class in Python's datetime module represents a duration or difference between two dates or times. This duration can be both positive and negative.

1. Basic Usage:

Here's how to create a timedelta object:

from datetime import timedelta # Create a timedelta of 10 days delta = timedelta(days=10) print(delta) # Outputs: 10 days, 0:00:00 

2. Parameters you can use:

The timedelta constructor can accept the following parameters:

  • days
  • seconds
  • microseconds
  • milliseconds
  • minutes
  • hours
  • weeks

For example:

delta = timedelta(days=1, seconds=3600) # Represents 1 day and 1 hour 

3. Operations:

You can perform arithmetic operations with timedelta objects:

# Addition delta1 = timedelta(days=1) delta2 = timedelta(days=2, hours=3) result = delta1 + delta2 print(result) # Outputs: 3 days, 3:00:00 # Subtraction result = delta2 - delta1 print(result) # Outputs: 1 day, 3:00:00 # Multiplication by integers or floats result = delta1 * 2 print(result) # Outputs: 2 days, 0:00:00 # Division by integers or floats result = delta2 / 2 print(result) # Outputs: 1 day, 1:30:00 

4. Interaction with datetime objects:

timedelta objects can be added or subtracted from datetime objects:

from datetime import datetime now = datetime.now() future = now + timedelta(days=5) past = now - timedelta(days=5) print(f"Today: {now}") print(f"Future: {future}") print(f"Past: {past}") 

5. Accessing Properties:

A timedelta object has three accessible attributes: days, seconds, and microseconds.

delta = timedelta(days=5, hours=3, minutes=20) print(delta.days) # Outputs: 5 print(delta.seconds) # Outputs: 12000 (3 hours and 20 minutes in seconds) print(delta.microseconds) # Outputs: 0 (since we haven't defined any) 

Note that timedelta internally stores durations in terms of days, seconds, and microseconds only. Even if you create a timedelta object using parameters like weeks, hours, or minutes, these are converted to days, seconds, and microseconds for internal storage.

6. Total seconds:

To get the total number of seconds represented by the timedelta, you can use the total_seconds method:

delta = timedelta(days=1, hours=1) print(delta.total_seconds()) # Outputs: 90000.0 

This provides a more comprehensive duration in seconds, rather than the split days/seconds/microseconds representation.


More Tags

splash-screen automatic-ref-counting subsonic protocols crm netsh go-map os.system android-proguard matplotlib-animation

More Programming Guides

Other Guides

More Programming Examples