Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: Display Nano Seconds With Date

Tags:

date

bash

With date it is possible to generate formatted time strings like

date +"%Y-%m-%d-%H:%M:%S.%N"

With date it is also possible to create unix timestamps in nano seconds. Using

NANO_TIMESTAMP=$(date +%s%N)

Is it possible to use date to read in a nano second timestamp to create a formatted date string?

How can I pass a nano second timestamp to date?

I tried:

date -d$NANO_TIMESTAMP +%H:%M:%S.%N     
date: invalid date ‘1550736813798767689’

date -d@$NANO_TIMESTAMP +"%Y-%m-%d-%H:%M:%S.%N"
date: time 1550736813798767689 is out of range
like image 320
jschnasse Avatar asked Sep 14 '25 00:09

jschnasse


2 Answers

You can do that by first by converting the nanosecond value in EPOCH to seconds value in EPOCH and then use that for conversion to human readable strings

nano=1550736813798767689
date -d@"$(( $nano / 1000000000 ))" +"%Y-%m-%d-%H:%M:%S.%N"

For even more accurate representation back, take the modulo of the nano second value

withNano="$(( $nano % 1000000000 ))"
withoutNano="$(date -d@"$(( $nano / 1000000000 ))" +"%Y-%m-%d-%H:%M:%S")"
echo "$withoutNano.$withNano"

So putting this together in a wrapper function

from_nano_to_readable() {
    (( $# )) || { printf '%s\n' 'provide atleast one argument' >&2 ; }
    input="$1"
    withNano="$(( $input % 1000000000 ))"
    withoutNano="$(date -d@"$(( $input / 1000000000 ))" +"%Y-%m-%d-%H:%M:%S")"
    printf '%s\n' "$withoutNano.$withNano"        
}

and call it as

from_nano_to_readable 1550736813798767690
2019-02-21-03:13:33.798767690
like image 186
Inian Avatar answered Sep 15 '25 13:09

Inian


Like this but without math.

NANO_TIMESTAMP=$(date +%s%N)
secs=$(printf "%1d\n" ${NANO_TIMESTAMP: 0 : -9})
nanos=${NANO_TIMESTAMP: -9 : 9 }
printf '\r%s' $(TZ=UTC date -d@$secs.$nanos +"%Y-%m-%d-%H:%M:%S.%N")

With printf "%1d" I want to make sure, that there is at least one zero in the secs variable.

like image 42
jschnasse Avatar answered Sep 15 '25 14:09

jschnasse