In python come faccio a riassumere la volta successiva?Tempo di somma Python
0:00:00
0:00:15
9:30:56
In python come faccio a riassumere la volta successiva?Tempo di somma Python
0:00:00
0:00:15
9:30:56
Come un elenco di stringhe?
timeList = [ '0:00:00', '0:00:15', '9:30:56' ]
totalSecs = 0
for tm in timeList:
timeParts = [int(s) for s in tm.split(':')]
totalSecs += (timeParts[0] * 60 + timeParts[1]) * 60 + timeParts[2]
totalSecs, sec = divmod(totalSecs, 60)
hr, min = divmod(totalSecs, 60)
print "%d:%02d:%02d" % (hr, min, sec)
Risultato:
9:31:11
Ho avuto questo in un array come stringhe come descritto ... Grazie .... – Hulk
+1 solo per dare 'divmod()' qualche airplay ... peccato che nessuno sia mai stato abbastanza coraggioso da richiedere a GvR di implementare '/%' e '/% =' operatori ;-) ... leggi questo e piangi: 'mins, secs /% = 60; ore, minuti /% = 60; giorni, ore /% = 24' –
@John: personalmente lo trovo illeggibile. Devi ricordare quale cosa sul LHS è il dividendo di input. Crea anche un caso in cui un operatore restituisce una tupla, che impedisce le operazioni di concatenamento, che è l'intero punto degli operatori binari. Trovo il modo 'divmod' un * lotto * più chiaro. –
Supponendo che si desidera aggiungere i secondi per un tempo totale:
def parse_time(s):
hour, min, sec = s.split(':')
try:
hour = int(hour)
min = int(min)
sec = int(sec)
except ValueError:
# handle errors here, but this isn't a bad default to ignore errors
return 0
return hour * 60 * 60 + min * 60 + sec
print parse_time('0:00:00') + parse_time('0:00:15') + parse_time('9:30:56')
approccio ingenuo (senza gestione delle eccezioni):
#!/usr/bin/env python
def sumup(*times):
cumulative = 0
for t in times:
hours, minutes, seconds = t.split(":")
cumulative += 3600 * int(hours) + 60 * int(minutes) + int(seconds)
return cumulative
def hms(seconds):
"""Turn seconds into hh:mm:ss"""
hours = seconds/3600
seconds -= 3600*hours
minutes = seconds/60
seconds -= 60*minutes
return "%02d:%02d:%02d" % (hours, minutes, seconds)
if __name__ == '__main__':
print hms(sumup(*("0:00:00", "0:00:15", "9:30:56")))
# will print: 09:31:11
Dipende dal modulo in cui ci sono questi orari, per esempio se già li avete come datetime.timedelta
s, allora si potrebbe semplicemente riassumere:
>>> s = datetime.timedelta(seconds=0) + datetime.timedelta(seconds=15) + datetime.timedelta(hours=9, minutes=30, seconds=56)
>>> str(s)
'9:31:11'
Penso che questa sia la soluzione più corretta usando delta – dassouki
lines = ["0:00:00", "0:00:15", "9:30:56"]
total = 0
for line in lines:
h, m, s = map(int, line.split(":"))
total += 3600*h + 60*m + s
print "%02d:%02d:%02d" % (total/3600, total/60 % 60, total % 60)
Sono veramente deluso se non v'è alcuna soluzione più divinatorio ... :(
orribile ->
timeList = [ '0:00:00', '0:00:15', '9:30:56' ]
ttt = [map(int,i.split()[-1].split(':')) for i in timeList]
seconds=reduce(lambda x,y:x+y[0]*3600+y[1]*60+y[2],ttt,0)
#seconds == 34271
Questo sembra orribile troppo ->
zero_time = datetime.datetime.strptime('0:0:0', '%H:%M:%S')
ttt=[datetime.datetime.strptime(i, '%H:%M:%S')-zero_time for i in timeList]
delta=sum(ttt,zero_time)-zero_time
# delta==datetime.timedelta(0, 34271)
# str(delta)=='9:31:11' # this seems good, but
# if we have more than 1 day we get for example str(delta)=='1 day, 1:05:22'
davvero frustrante è anche questo ->
sum(ttt,zero_time).strftime('%H:%M:%S') # it is only "modulo" 24 :(
Mi piace molto vedere one-liner così, ho cercato di fare uno in python3: P (buon risultato, ma orribile aspetto)
import functools
timeList = ['0:00:00','0:00:15','9:30:56','21:00:00'] # notice additional 21 hours!
sum_fnc=lambda ttt:(lambda a:'%02d:%02d:%02d' % (divmod(divmod(a,60)[0],60)+(divmod(a,60)[1],)))((lambda a:functools.reduce(lambda x,y:x+y[0]*3600+y[1]*60+y[2],a,0))((lambda a:[list(map(int,i.split()[-1].split(':'))) for i in a])(ttt)))
# sum_fnc(timeList) -> '30:40:11'
utilizzando timedeltas (testato in Python 3.4):
import datetime
timeList = ['0:00:00', '0:00:15', '9:30:56']
sum = datetime.timedelta()
for i in timeList:
(h, m, s) = i.split(':')
d = datetime.timedelta(hours=int(h), minutes=int(m), seconds=int(s))
sum += d
print(str(sum))
Risultato:
9:31:11
Funziona anche in 2.7. +1 perché il codice è leggibile e intuitivo – adelval
Bellow è una soluzione che utilizza ridurre e di lista:
from functools import reduce
from datetime import timedelta
time_list = ['0:00:00', '0:00:15', '9:30:56']
total = reduce(lambda x, y: x + y,
[timedelta(hours=int(ms[0]), minutes=int(ms[1]), seconds=int(ms[2]))
for t in time_list
for ms in [t.split(':')]])
print(f'Total time: {total}')
Tempo totale: 9:31:11
Presumo che si desidera aggiungere le differenze dalla 00:00:00? cioè, i delta, piuttosto che i tempi effettivi? –
@steve: beh, i delta aggiungerebbero a '9: 30: 56' – SilentGhost
sto usando python 2.4 e non posso usare strptime, sì voglio aggiungere i delta e per l'esempio sopra menzionato la risposta dovrebbe essere 9 : 31: 11 – Hulk