Working with durations

Working with Dates and Times in Python

Max Shron

Data Scientist and Author

Working with durations

Working with Dates and Times in Python

Working with durations

# Create example datetimes
start = datetime(2017, 10, 8, 23, 46, 47)
end = datetime(2017, 10, 9, 0, 10, 57)
# Subtract datetimes to create a timedelta
duration = end - start
Working with Dates and Times in Python

Working with durations

# Subtract datetimes to create a timedelta
print(duration.total_seconds())
1450.0
Working with Dates and Times in Python

Creating timedeltas

# Import timedelta
from datetime import timedelta
# Create a timedelta
delta1 = timedelta(seconds=1)
Working with Dates and Times in Python

Creating timedeltas

print(start)
2017-10-08 23:46:47
# One second later
print(start + delta1)
2017-10-08 23:46:48
Working with Dates and Times in Python

Creating timedeltas

# Create a one day and one second timedelta
delta2 = timedelta(days=1, seconds=1)
print(start)
2017-10-08 23:46:47
# One day and one second later
print(start + delta2)
2017-10-09 23:46:48
Working with Dates and Times in Python

Negative timedeltas

# Create a negative timedelta of one week
delta3 = timedelta(weeks=-1)
print(start)
2017-10-08 23:46:47
# One week earlier
print(start + delta3)
2017-10-01 23:46:47
Working with Dates and Times in Python

Negative timedeltas

# Same, but we'll subtract this time
delta4 = timedelta(weeks=1)
print(start)
2017-10-08 23:46:47
# One week earlier
print(start - delta4)
2017-10-01 23:46:47
Working with Dates and Times in Python

Working with durations

Working with Dates and Times in Python

Preparing Video For Download...