How can someone print the entire time ie, for example 12:07:59:393(HH:MM:SS:milliseconds) in milliseconds. I found a lot of posts saying how to print Milliseconds along witht HHMMSS but I want to print the realtime clock in milliseconds. I'm using Linux.

  • Are you interested in the entire wall clock run-time for programs started by the shell or are you interested in the time-of day-value with millisecond granularity? – schily May 2 '16 at 15:26
  • I am printing log packets and I need the timestamp to be in milliseconds when i print each line (wallclock precision) not time-of-day-value with millisecond granularity – RajuBhai May 2 '16 at 15:30
  • 1
    If you are looking for a portable method, then the answer is: no, there is no way to do that. If you are on linux only, you may use date. – schily May 2 '16 at 15:32

This will give you how many miliseconds have passed since the beginning of the Unix epoch :

date +%s%3N

You have to reduce the seconds*1000 which have passed until 00:00 AM today. Or you can just convert everything into miliseconds from this formula :

date +%H%M%S%3N

Like :

h=$(date +%H)
m=$(date +%M)
s=$(date +%S)
ms=$(date +%3N)
echo $((10#$h*3600000 + 10#$m*60000 + 10#$s*1000 + 10#$ms))

Executing this took me 4 miliseconds in average, you might want ot reduce that time.

Edit : If there is a leading zero in one of the variables the script will fail. I added 10# in front of the variable names, to strip the leading zeros, so that we get, for example, 8 instead of 08.

  • 1
    date +%s is non-portable and there is no portable way to retrieve more than second granularity from date. – schily May 2 '16 at 15:30
  • 5
    the question is tagged /linux. your anti-GNU prejudice is not applicable here. – cas May 2 '16 at 20:21

See if perl is portable enough:

perl -MTime::HiRes=time -MPOSIX=strftime -e '
    $now = int(time() * 1000);
    printf "%s.%03d\n", strftime("%H:%M:%S", localtime(int($now/1000))), ($now % 1000);

Time::HiRes and POSIX are both core Perl modules.

If you just want the epoch timestamp with fractional seconds:

$ perl -MTime::HiRes=time -le 'print time()'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.