Peter S
Peter S

Reputation: 575

Convert TimeStamp from LogFile

My LogFile:

created_at,entry_id,field1
2017-09-08 13:21:12 UTC,69,39.00
2017-09-08 14:20:03 UTC,70,42.00
2017-09-08 15:18:32 UTC,71,43.00
2017-09-08 16:16:59 UTC,72,44.00
2017-09-08 17:15:53 UTC,73,44.00

I would like to rewrite the LogFile, convert the TimeStamp from UTC into GMT +2, and replace the , with Tabs.

What's the best way to convert the timestamp and replace c with bash?

Upvotes: 0

Views: 623

Answers (2)

glenn jackman
glenn jackman

Reputation: 246847

quick and dirty:

perl -MTime::Piece -F, -ane '
    if ($. > 1) {
        $t = Time::Piece->strptime($F[0], "%Y-%m-%d %T UTC"); 
        $F[0] = ($t + 7200)->strftime("%Y-%m-%d %T+02:00");
    }
    print join "\t", @F
' file

If I wanted to do this a bit more robustly, and use an Olson timezone to handle daylight saving, I would use non-core modules and do:

perl -MDateTime::Format::Strptime -F, -sane '
  BEGIN {
    $fmt = "%F %T %Z";
    $p = DateTime::Format::Strptime->new(pattern => $fmt, time_zone => "UTC");
  }
  if ($. > 1) {
    $t = $p->parse_datetime($F[0]);
    $F[0] = $t->set_time_zone($dest_tz)->strftime($fmt);
  }                                                        
  print join "\t", @F
' -- -dest_tz="Europe/Paris" file
created_at  entry_id    field1
2017-09-08 15:21:12 CEST    69  39.00
2017-09-08 16:20:03 CEST    70  42.00
2017-09-08 17:18:32 CEST    71  43.00
2017-09-08 18:16:59 CEST    72  44.00
2017-09-08 19:15:53 CEST    73  44.00

Adjust your destination timezone to suit.

Upvotes: 1

Cyrus
Cyrus

Reputation: 88644

A possible implementation:

#!/bin/bash

while IFS=, read c1 c2 c3; do 
  if [[ $c1 == "created_at" ]]; then echo -e "$c1\t$c2\t$c3"; continue; fi
  TZ=UTC date -d "$c1 +2hours" +"%Y-%m-%d %T"$'\t'"$c2"$'\t'"$c3"
done < file

Output:

created_at      entry_id        field1
2017-09-08 15:21:12     69      39.00
2017-09-08 16:20:03     70      42.00
2017-09-08 17:18:32     71      43.00
2017-09-08 18:16:59     72      44.00
2017-09-08 19:15:53     73      44.00

Disadvantage: slow

Upvotes: 2

Related Questions