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
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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With