Search code examples
ubuntuawkutcstrftime

How to convert Timestamp in UTC time using AWK


I try to process a mail log file using awk, but I have an issue with the conversion of the Timestamp into an UTC format.

The Input file looks like :

# cat /tmp/TimeStamps1.tmp

2016-08-10T00:23:45.984558+02:00
2016-09-30T10:23:45.984558+02:00
2016-10-31T20:45:27.984558+01:00

And the expect output should be :

cat /tmp/Target

2016-08-09 22:23:45
2016-09-30 08:23:45
2016-10-31 19:45:27

As the "T" between Date & Time seems an issue, I also tried to remove it :

# cat /tmp/TimeStamps2.tmp

2016-08-10 00:23:45.984558+02:00
2016-09-30 10:23:45.984558+02:00
2016-10-31 20:45:27.984558+01:00

First try using system()

awk ' {print $1" - "system("date -u +%Y-%m-%d -d" $0) } ' /tmp/TimeStamps2.tmp
date: extra operand `00:23:45.984558+02:00'
Try `date --help' for more information.
2016-08-10 - 1
date: extra operand `10:23:45.984558+02:00'
Try `date --help' for more information.
2016-09-30 - 1
date: extra operand `20:45:27.984558+01:00'
Try `date --help' for more information.
2016-10-31 - 1

Second try using strftime()

/tmp$ awk -F',' ' {print $1" - "strftime( "%Y-%m-%d %H:%M:%S", $1)} ' /tmp/TimeStamps2.tmp
2016-08-10 00:23:45.984558+02:00 - 1970-01-01 01:33:36
2016-09-30 10:23:45.984558+02:00 - 1970-01-01 01:33:36
2016-10-31 20:45:27.984558+01:00 - 1970-01-01 01:33:36

Solution

  • It now sounds like this is what you're really trying to do:

    $ cat file
    2016-08-10T00:23:45.984558+02:00 here is the first line
    2016-09-30T10:23:45.984558+02:00 and here's the second
    2016-10-31T20:45:27.984558+01:00 oh look, a third!
    
    $ awk '{
        ts=$1; sub(/T/," ",ts); sub(/[^ ]+ /,"")
        cmd="date -u +\"%Y-%m-%d %T\" -d \"" ts "\""
        if ((cmd | getline line) > 0) {
            print line, $0
        }
        close(cmd)
    }' file
    2016-08-09 22:23:45 here is the first line
    2016-09-30 08:23:45 and here's the second
    2016-10-31 19:45:27 oh look, a third!