How to command "Ping" display time and date of ping

Use:

ping www.google.fr | while read pong; do echo "$(date): $pong"; done

You will get the result like this:

enter image description here


1. time from ping -D

Another possibility to use the ping -D option which gets you the timestamp as Unix time.

tilo@t-ubuntu:~$ ping google.com -D
PING google.com (173.194.33.73) 56(84) bytes of data.
[1388886989.442413] 64 bytes from sea09s15-in-f9.1e100.net (173.194.33.73): icmp_req=1 ttl=57 time=11.1 ms
[1388886990.443845] 64 bytes from sea09s15-in-f9.1e100.net (173.194.33.73): icmp_req=2 ttl=57 time=11.0 ms
[1388886991.445200] 64 bytes from sea09s15-in-f9.1e100.net (173.194.33.73): icmp_req=3 ttl=57 time=10.8 ms
[1388886992.446617] 64 bytes from sea09s15-in-f9.1e100.net (173.194.33.73): icmp_req=4 ttl=57 time=10.9 ms
^C
--- google.com ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3004ms
rtt min/avg/max/mdev = 10.860/11.005/11.139/0.123 ms
tilo@t-ubuntu:~$ 

here is a awk cmd to parse timestamp to date format:

$ ping -D 10.1.1.1 | awk '{ if(gsub(/\[|\]/, "", $1)) $1=strftime("[%F %T]", $1); print}'
PING 10.1.1.1 (10.1.1.1) 56(84) bytes of data.
[2020-04-10 19:25:08] 64 bytes from 10.1.1.1: icmp_seq=1 ttl=63 time=14.1 ms
[2020-04-10 19:25:09] 64 bytes from 10.1.1.1: icmp_seq=2 ttl=63 time=12.9 ms
[2020-04-10 19:25:10] 64 bytes from 10.1.1.1: icmp_seq=3 ttl=63 time=12.0 ms
^C

PS: awk may full-buffered with pipe, a fflush() after print will fix:

ping.ts(){
    if [ -t 1 ]; then
        ping -D "$@" | awk '{ if(gsub(/\[|\]/, "", $1)) $1=strftime("[\033[34m%F %T\033[0m]", $1); print; fflush()}'
    else
        ping -D "$@" | awk '{ if(gsub(/\[|\]/, "", $1)) $1=strftime("[%F %T]", $1); print; fflush()}'
    fi  
}

2. time from date

Here a version of "Achu" command with slightly different format:

ping www.google.com -i 10 -c 3000 | while read pong; do echo "$(date +%Y-%m-%d_%H%M%S): $pong"; done >PingTest_2014-01-04.log

That gets you:

2014-01-04_175748: 64 bytes from sea09s16-in-f19.1e100.net (173.194.33.115): icmp_req=13 ttl=57 time=10.5 ms

There is a utility called ts, which reads stdin, adds timestamps, and writes it to stdout:

me@my-laptop:~$ ping localhost | ts
Nov 08 09:15:41 PING localhost (127.0.0.1) 56(84) bytes of data.
Nov 08 09:15:41 64 bytes from localhost (127.0.0.1): icmp_seq=1 ttl=64 time=0.060 ms
Nov 08 09:15:42 64 bytes from localhost (127.0.0.1): icmp_seq=2 ttl=64 time=0.098 ms
Nov 08 09:15:43 64 bytes from localhost (127.0.0.1): icmp_seq=3 ttl=64 time=0.082 ms
Nov 08 09:15:44 64 bytes from localhost (127.0.0.1): icmp_seq=4 ttl=64 time=0.091 ms

It can be installed in Ubuntu with sudo apt install moreutils.