Home > OS >  Iterating datetime function over a list
Iterating datetime function over a list

Time:12-03

I am using Python 2.7 within another application. I have a list of timestamps in the following format. The length of the list will vary per task:

['23:05:26', '23:05:28', '23:05:30', '23:05:32']

Using datetime I would like to run some basic maths on this list making use of timedelta

So far I have successfully run the operation on two individual timestamps, but I cannot find the correct syntax and or method to iterate the same function over a list.

My basic function is

def TS(x): 
    z1 = datetime.strptime(x, '%H:%M:%S')
    z2 = timedelta(hours=z1.hour,minutes=z1.minute,seconds=z1.second)

When the strings are converted to timedeltas I plan to perform the following calculation (but not sure if it should be in the same loop as setting the timedelta):

x[-1] - x[-2], x[-2] - x[-3], ...

and then store the result of each of these calculations as both a string, using str(ResultOfTimeCalc), and also as seconds, which I guess I should do using ResultOfTimeCalc.seconds.

How can I format this all, what needs to be done in a loop, and how to iterate a function within a loop?

CodePudding user response:

There's no need to call timedelta explicitly. You can subtract two datetime objects to get the difference as a timedelta.

>>> times = ['23:05:26', '23:05:28', '23:05:30', '23:05:32']
>>> from datetime import datetime
>>> tses = [datetime.strptime(x, '%H:%M:%S') for x in times]
>>> [y - x for x, y in zip(tses, tses[1:])]
[datetime.timedelta(seconds=2), datetime.timedelta(seconds=2), datetime.timedelta(seconds=2)]

CodePudding user response:

Edited: I combined it with the TS(x) function to output the timedeltas in seconds.

If "x" is a list of timestamps, then to calculate the differences between adjacent time points, from the most recent time point to the first time point:

[(datetime.datetime.strptime(x[-index], '%H:%M:%S') - datetime.datetime.strptime(x[-(index   1)], '%H:%M:%S')).seconds for index in np.arange(1, len(x), 1)]
  • Related