Getting date in seconds with decimals

I am trying to get date to display decimal
Desired output 1350386096256.12

I know this can be done with printf , but are not able to make it work.

I have tested this and many other

printf "%.2f" $(($(date +%s%N)/1000000))

Try like

date +%s%N|awk '{printf "%.2f",$0}'

---------- Post updated at 06:37 AM ---------- Previous update was at 06:36 AM ----------

same as added new line

date +%s%N|awk '{printf "%.2f\n",$0}'
printf "%0.2f\n" $(date +%s.%N)
1350386830.08

The %N nanosecond format is just the nanosecond offset, it is formatted output rather than a precision flag

1 Like

I think it's because the shell uses integer arithmetics. Use it in a command that has floating arithmetics, you'll get your decimals:

date +%s%N|awk '{printf "%.2f\n", $0/1000000000}'
1350387489.16

I think bash doesn't support floating point arithmetic. ksh93 does.
You may use ksh93 or bc or awk (as bmk suggested).
You may use bmk's solution with a slight modification:

awk 'BEGIN{"date +%s%N"|getline;printf "%.2f\n",($1/1000000000)}'

Thanks
My goal is to have time in a variable like t1
Then some later in the script get the time again t2
Then calculate the difference in seconds having two decimal.
I do prefer it to work in sh or bash
echo $(($t2-$t1)) does not work with decimal bash
So having it to work in awk would be good.

You could try

echo "`date '+%s%N'` / 1000000" | bc -l

Solution that seems to work.

t1=$(date +%s%N | awk '{printf "%.2f",$0/1000000000}')
# some code
# some more code
diff=$(echo "" | awk '{printf "%.2f\n", t2-t1}' t1=$t1 t2=$(date +%s%N | awk '{printf "%.2f",$0/1000000000}'))

Seems that AWK need some input to work, so added echo ""

bc is not installed by default in my system, so I will not use it.

If you will not be reading any stream with awk , you can just have the BEGIN block. That way awk won't try to read any input and you can drop the pipe with echo .

1 Like