简体   繁体   中英

Python sum time from file txt

I'm using a script:

import sys
sys.argv
 
entry = 2

t = 0
SEC = 0
min = 0
hrs = 0
 
with open (sys.argv [1]) as fp:
     for in line fp:
         entry+=1
         if entry% 8:
             continue
 
         t + = int (line)
 
sec = t% 60
t // = 60
min = t% 60
hrs = t // 60
 
print ("Total time:% d hours% 02d minutes% 02d seconds"% (hrs, min, sec)

Entrance:

315: 31: 54 0:00:32 1:11:24 8:18:18 111: 35: 56 112: 45: 26 0:21:33

of course much bigger;)

And there is an error:

invalid literal for int() with base 10: '112:45:26\\n'

I checked 10x. There are no white characters in the input txt file. So what is the cause?

11:30:22 is not a parseable to integer string. You need first to convert your strings to timestamps, which can easely be done with time package

>>> import time
>>> import datetime
>>> s = "01:12:20"
>>> time.mktime(datetime.datetime.strptime(s, "%h:%M:%s").timetuple())

The answer will be a numerical value which you can work with. You could also look in deltatime which may help you in your work

After giving some tought, the best approach for this situation is a custom converter instead of trying to adapt the ones present at Python std library

# you should change this to an open file - read()
dataset = """315:31:54
        00:00:32
        01:11:24
        08:18:18
        111:35:56
        112:45:26"""

acc = 0

# unfortunatelly this is a non-standard dataset of timestamps, therefore
# the best approach is to create your own converter

for line in dataset.split():
    split_time = line.split(":")
    acc += int(split_time [0]) * 60 * 60 + int(split_time [1]) * 60 + int(split_time[2])


print("total in seconds:", acc) 

>>> total in seconds: 1977810

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM