Home > Back-end >  How can I add n number of datetime.strptime in "%I:%M:%S" format stored in a list in pytho
How can I add n number of datetime.strptime in "%I:%M:%S" format stored in a list in pytho

Time:09-24

I've n number of datetime.strptime items stored in a list in "%I:%M:%S" format

total_logs = ['0:00:12', '0:10:02', , , n]

How can I add them?

CodePudding user response:

I would use the Timedelta class from pandas to do this.

import pandas as pd

logs = ['0:00:12', '0:10:02']
r = pd.Timedelta(logs[0])   pd.Timedelta(logs[1])
print(r)

Output: 0 days 00:10:14

Python's datetime.timedelta could also do the job, but it doesn't work on strings directly. You have to convert them using datetime.datetime.strptime first.

To sum all the items in the list, you have to start from a starting point, in the following code it is r, then you iterate over the list and you add to r:

In [37]: r = pd.Timedelta(0)

In [38]: r
Out[38]: Timedelta('0 days 00:00:00')

In [39]: for item in logs:
    ...:     r  = pd.Timedelta(item)
    ...:

In [40]: print(r)
0 days 00:10:14

The one-liner for the whole think would be: sum(map(pd.Timedelta, logs), pd.Timedelta(0))

  • Related