'bash script - how to get the time difference (in hour:minute:seconds) between two unix-timestamps
I need to get the time difference between two unix-timestamps in hour, minute, and seconds. I can get the different in minutes and seconds correctly but the hour is always wrong.
I have two unix-timestamps and I subtract to get the difference.
1595455100 - 1595452147 = 2953 (That's the time difference between 2:09:07pm and 2:58:20pm on the same day)
Then I do date -d @2953 +'%I:%M:%S'
I get 04:49:13 but I expect to get 0:49:13
I'd also tried date -d @2953 +'%H:%M:%S' and date -d @2953 +'%T' and get 16:49:13. I've also checked differences greater than an hour, the difference in minute and seconds is still correct but the hour is still wrong.
I don't understand the Hour format and appreciate any help.
Solution 1:[1]
You don't necessarily need date for this conversion. You can use integer math and printf for fun and profit.
start=1595452147
end=1595455100
s=$((end - start))
time=$(printf %02d:%02d:%02d $((s / 3600)) $((s / 60 % 60)) $((s % 60)))
echo $time
There may be a way to do it with date too, but the above should work reliably.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Pi Marillion |
