Convert a time span in seconds to formatted time in shell

后端 未结 7 1997
鱼传尺愫
鱼传尺愫 2020-12-28 13:25

I have a variable of $i which is seconds in a shell script, and I am trying to convert it to 24 HOUR HH:MM:SS. Is this possible in shell?

7条回答
  •  渐次进展
    2020-12-28 14:11

    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!

提交回复
热议问题