Home > Back-end >  SHELL: How can I convert a string to timestamp
SHELL: How can I convert a string to timestamp

Time:04-05

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?

CodePudding user response:

With bash, using the builtin arithmetic

str=38740
(( mins = str / 60000, str %= 60000, secs = str / 1000, msec = str % 1000 ))
printf -v duration "d:d.d" "$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 "d:d.d\n" "$mins" "$secs" "$msec"
}

then

$ milliseconds_to_duration 38740
00:38.740

CodePudding user response:

Another Bash approach

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