How can I convert unix timestamp to hh:mm:ss:SSS (where SSS is milliseconds) in AWK.

For example:

echo 1456478048306 > time
cat time | awk ....... > readable_time_format

With GNU date:


date -d "@$s" +"%F %T.$ms %z"
# or:
date -d "$s.$ms" '+%F %T.%3N %z'

With BSD date:

date -r "$s" +"%F %T.$ms %z"

With GNU awk and recent versions of mawk (since 1.3.4 20121129):

echo 1456478048306 | awk '{
  print strftime("%F %T." substr($0,length-2) " %z", substr($0, 1, length-3))}'

For portability, perl may be your best bet:

echo 1456478048306 | perl -MPOSIX -lne '
  print strftime "%F %T.$2 %z", localtime $1 if /(.+)(.{3})/'

Here giving my preferred more conventional and less ambiguous format:

2016-02-26 09:14:08.306 +0000

but of course, you can adjust the strftime format to your preference.

| improve this answer | |
  • mawk (except Debian of course) provides strftime since late 2012. ymmv. – Thomas Dickey Feb 26 '16 at 11:04
  • @ThomasDickey. Thanks, added. You have a typo in the CHANGES file btw (s/strtime/strftime/). – Stéphane Chazelas Feb 26 '16 at 11:50
  • I noticed that when I commented... – Thomas Dickey Feb 26 '16 at 21:28

If you are unconcerned about timezones and leap seconds, and for some reason your awk does not support strftime, you can calculate it directly:

awk '{ t=$1;sss=(t % 1000); t/=1000; ss=(t%60); t/=60; mm=(t%60);
  t/=60; hh=(t%24); printf("%02d:%02d:%02d.%03d\n",hh,mm,ss,sss); }'
| improve this answer | |

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.