Jean S.
Jean S.

Reputation: 35

Convert all Unix Time in a file to human date

I want to replace all the UNIX time in a a JSON data file with the same UNIX time followed by a human readable date format.

For example, I want to replace "1234567890123456" (time in microsecond) with "1234567890123456,2009-02-14,00:31:30,sat".

I tried with

sed -r 's/([0-9]{16})/\1'"`date -d @ \1`"'/g'

but it doesn't work. I'm new in UNIX world, can you suggest me a solution? Thank you so much.

Cordiality

I attach a sample of my JSON file:

{
  "example": [
    {
      "query": {
        "text": "string 1",
        "id": [
          {
            "timestamp": "1234567890123456"
          }
        ]
      }
    },
    {
      "query": {
        "text": "string 2",
        "id": [
          {
            "timestamp": "1234567891123456"
          }
        ]
      }
    },
    {
      "query": {
        "text": "string 3",
        "id": [
          {
            "timestamp": "1234567893123456"
          }
        ]
      }
    }
  ]
}

Upvotes: 0

Views: 819

Answers (2)

Ed Morton
Ed Morton

Reputation: 203899

Is this what you're looking for?

$ gawk -F'"' '/timestamp/{sub($(NF-1),"&,"strftime("%Y-%m-%d,%H:%M:%S,%a",int($(NF-1)/1000000)))} 1' file
{
  "example": [
    {
      "query": {
        "text": "string 1",
        "id": [
          {
            "timestamp": "1234567890123456,2009-02-13,17:31:30,Fri"
          }
        ]
      }
    },
    {
      "query": {
        "text": "string 2",
        "id": [
          {
            "timestamp": "1234567891123456,2009-02-13,17:31:31,Fri"
          }
        ]
      }
    },
    {
      "query": {
        "text": "string 3",
        "id": [
          {
            "timestamp": "1234567893123456,2009-02-13,17:31:33,Fri"
          }
        ]
      }
    }
  ]
}

If not, post the expected output to go with your sample input so we're not playing a guessing game.

Upvotes: 1

Pubci
Pubci

Reputation: 4001

You can use date command as below.

1.To get the current time - date +'%s,%Y-%m-%d,%H:%M:%S:,%a'

2.To get a specific time - date -d @1234567890 +'%s,%Y-%m-%d,%H:%M:%S:,%a

Upvotes: 0

Related Questions