Convert Time String (HH:MM:SS) To Seconds

Sometimes it is necessary to find the amount of seconds in a time string for use in equations. Below are PHP and Python functions to do this. These functions work by splitting the time string by ‘:’, then calculating 60 to the power of the split time count minus 1 (allowing for MM:SS format and SS format). Split time is then looped and the individual parts are multiplied by the current modifier (the previous 60^[len(split_time)-1]); the modifier is then divided by 60 for the next iteration.
==PHP==
{{{ lang=php line=1
/*
* Convert time to seconds
*
* @param Str $time Time str (format HH:MM:SS)
*
* @return Int Amount of seconds
*/
function time_to_seconds($time){
$split_time = explode(‘:’, $time);
$modifier = pow(60, count($split_time) – 1);
$seconds = 0;
foreach($split_time as $time_part){
$seconds += ($time_part * $modifier);
$modifier /= 60;
}
return $seconds;
}
}}}
==Python==
{{{ lang=python line=1
## Convert time to seconds
#
# @param Str $time Time str (format HH:MM:SS)
#
# @return Int Amount of seconds
import math
def time_to_seconds(time):
split_time = time.split(‘:’)
modifier = math.pow(60, len(split_time) )
seconds = 0
for time_part in split_time:
seconds += (time_part * modifier)
modifier /= 60
return seconds
}}}


Posted

in

,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *