Zirc
Zirc

Reputation: 470

Python Time Subtraction Resulting into Time Tuple

I want to subtract 2 times and convert that into a time array.

I consulted this How to calculate the time interval between two time strings. Stating this following code

from datetime import datetime as dt
import time

print("Time Subtraction")
FMT = '%Y-%m-%d %H:%M:%S'
time_tuple = (2018, 1, 13, 13, 51, 18, 2, 317, 0)
time2_tuple = (2018, 1, 15, 13, 50, 18, 2, 317, 0)
s1 = time.strftime(FMT, time_tuple)
s2 = time.strftime(FMT, time2_tuple)

tdelta = dt.strptime(s2, FMT) - dt.strptime(s1, FMT)
print(tdelta)

The result is:

Time Subtraction
1 day, 23:59:00

But I want to get a tuple/print that will look like this

tuple = (0,0,1,23,59,0,2,317,0)

I usually use time not datetime so I am not sure what to do. Any ideas?

Upvotes: 1

Views: 246

Answers (1)

J. Blackadar
J. Blackadar

Reputation: 1951

tdelta is a datetime.timedelta object, therefore you are printing the string representation of that object. You can get the days, hours, minutes, etc by performing simple arithmetic (since they are stored as fractions-of-days) on the attributes:

def days_hours_minutes(delta):
    return delta.days, delta.seconds//3600, (delta.seconds//60)%60

You can add as many of these attributes to the tuple as you'd like.

Upvotes: 1

Related Questions