Convert a Time Span in Seconds to Formatted Time in Shell

Convert a time span in seconds to formatted time in shell

Here's a fun hacky way to do exactly what you are looking for =)

date -u -d @${i} +"%T"

Explanation:

  • The date utility allows you to specify a time, from string, in seconds since 1970-01-01 00:00:00 UTC, and output it in whatever format you specify.
  • The -u option is to display UTC time, so it doesn't factor in timezone offsets (since start time from 1970 is in UTC)
  • The following parts are GNU date-specific (Linux):

    • The -d part tells date to accept the time information from string instead of using now
    • The @${i} part is how you tell date that $i is in seconds
  • The +"%T" is for formatting your output. From the man date page: %T time; same as %H:%M:%S. Since we only care about the HH:MM:SS part, this fits!

Convert seconds to hours, minutes, seconds

I use the following function myself:

function show_time () {
num=$1
min=0
hour=0
day=0
if((num>59));then
((sec=num%60))
((num=num/60))
if((num>59));then
((min=num%60))
((num=num/60))
if((num>23));then
((hour=num%24))
((day=num/24))
else
((hour=num))
fi
else
((min=num))
fi
else
((sec=num))
fi
echo "$day"d "$hour"h "$min"m "$sec"s
}

Note it counts days as well. Also, it shows a different result for your last number.

Bash - convert time interval string to nr. of seconds

You could start at epoch

date -d"1970-01-01 00:00:00 UTC 5 minutes 10 seconds" "+%s"
310

You could also easily sub in times

Time="1 day"
date -d"1970-01-01 00:00:00 UTC $Time" "+%s"
86400

how to convert a date HH: MM: SS in second with bash?


date +%s

returns the current datetime in seconds since 1970-01-01 00:00:00 UTC

if you want to get a given datetime in seconds since 1970-01-01 00:00:00 UTC, for example:

kent$  date -d"2008-08-08 20:20:20" +%s
1218219620

to get diff in seconds, you just get the two dates in seconds, and do a s1-s2

How to convert time period string in sleep format to seconds in bash

When you replace the letters with the corresponding factors, you can pipe that to bc. You only need to take care of the + at the end of the line.

t2s() {
sed 's/d/*24*3600 +/g; s/h/*3600 +/g; s/m/*60 +/g; s/s/\+/g; s/+[ ]*$//g' <<< "$1" | bc
}

Testrun

$ t2s "3d 7h 5m 10s"
284710
$ t2s "3d 7h 5m "
284700
$ t2s "3s 5s 6h"
21608


Related Topics



Leave a reply



Submit