'SHELL: How can I convert a string to timestamp

I'd like to convert string below into timestamp, I already did this into Sheets but I would like to automate this process.

FROM: 38740

TO: 00:38.74

In google sheets, I insert the formula and works perfectly

=TEXT(A2/86400000,"mm:ss.00")

In shell (bash):

awk "BEGIN {print 38740/86400000}"

There's one way to do that using shell or I need to use some programming language more advanced?



Solution 1:[1]

Another Bash approach

t=$(bc <<< 'scale=2; 38740/1000')
d=$(date -d @"$t" --utc '+%M:%S.%N')
echo "${d:0:9}"
00:38.740

Solution 2:[2]

With bash, using the builtin arithmetic

str=38740
(( mins = str / 60000, str %= 60000, secs = str / 1000, msec = str % 1000 ))
printf -v duration "%02d:%02d.%03d" "$mins" "$secs" "$msec"
echo "$duration"
# => 00:38.740

Encapsulated into a function:

milliseconds_to_duration () {
    local mins secs msec
    local tmp=$1
    (( mins = tmp / 60000, tmp %= 60000, secs = tmp / 1000, msec = tmp % 1000 ))
    printf "%02d:%02d.%03d\n" "$mins" "$secs" "$msec"
}

then

$ milliseconds_to_duration 38740
00:38.740

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 LMC
Solution 2 glenn jackman