Reputation: 87
What I am trying to do is take two lists of time stamps, find the difference between the corresponding time stamp pairs, and then print the differences as another list. When I print the final list of time differences I get this:
[datetime.timedelta(0, 2700), datetime.timedelta(0, 1800)]
Here is my code for reference:
import time
import datetime
strlist1 = ['12:45:00', '01:30:00']
format = '%H:%M:%S'
i = 0
timelist1 = []
for time in strlist1:
timelist1.append(datetime.datetime.strptime(strlist1[i], format))
i += 1
strlist2 = ['12:00:00', '01:00:00']
k = 0
timelist2 = []
for time in strlist2:
timelist2.append(datetime.datetime.strptime(strlist2[k], format))
k += 1
list3 = [x1 - x2 for (x1, x2) in zip(timelist1, timelist2)]
Also, I am fairly new to Python, so any other constructive input on ways to improve and/or change anything else is greatly appreciated. Thank you!
Upvotes: 1
Views: 766
Reputation: 10208
Here's a start. In Python there's no need for a counter when you iterate over a sequence, so the variables i
and k
are not needed. As wim pointed out, you probably want a string representation of the output. Finally, you can just generate the lists with a list comprehension instead of the loop.
import time
import datetime
strlist1 = ['12:45:00', '01:30:00']
format = '%H:%M:%S'
# i = 0 Not needed
timelist1 = [datetime.datetime.strptime(s, format) for s in strlist1]
strlist2 = ['12:00:00', '01:00:00']
timelist2 = [datetime.datetime.strptime(s, format) for s in strlist2]
list3 = [str(x1 - x2) for (x1, x2) in zip(timelist1, timelist2)]
Upvotes: 1
Reputation: 19947
This should give you a more readable format:
[((datetime.datetime.strptime('00:00:00', format))+e).strftime(format) for e in list3]
Out[340]: ['00:45:00', '00:30:00']
Upvotes: 1
Reputation: 362507
List elements will use the repr
, and the repr
is not usually human readable.
>>> L = [datetime.timedelta(0, 2700), datetime.timedelta(0, 1800)]
>>> L
[datetime.timedelta(0, 2700), datetime.timedelta(0, 1800)]
You want:
>>> map(str, L) # or: [str(delta) for delta in L]
['0:45:00', '0:30:00']
Upvotes: 1