1

When using the AWS get-metric-statistics command, the following timestamp format is returned.

2021-06-23T09:48:00Z

This time is in UTC 0, and I want to convert this value to a unix timestamp In Shell Script.
I tried a lot of this and that, but it didn't work.
So, I ask for your help... Thank you.

What I tried
utctimestamp=`TZ=UTC date -d "$timestamp" +%s `
=> date: invalid date ‘"2021-06-23T10:12:00Z"’

utctimestamp=$(TZ="UTC" date -j -f "+%Y-%m-%dT%H:%M:%SZ" "$timestamp" "+%s")
=> date: invalid option -- 'j'

utctimestamp=`date -d -u "$timestamp" +%s `
=> date: invalid date ‘"2021-06-23T10:12:00Z"’

and so on..

Biffen
  • 6,249
  • 6
  • 28
  • 36
P.Lonnie
  • 105
  • 2
  • 11
  • What did you try? Please post it. Do you want the value in EPOCH? – Inian Jun 23 '21 at 10:11
  • https://stackoverflow.com/questions/21778251/convert-an-iso-date-to-seconds-since-epoch-in-linux-bash https://stackoverflow.com/questions/55768882/converting-date-with-timezone-in-unix-timestamp-shell-bash – KamilCuk Jun 23 '21 at 10:16
  • `invalid date ‘"2021-06-23T10:12:00Z"’ ` You date variable contains `2021-06-23T09:48:00Z` __or__ `"2021-06-23T09:48:00Z"`? Remove the quotes from it. – KamilCuk Jun 23 '21 at 10:22
  • Thank you so much for your help. When AWS returns timestamp, it is returned with double quotation marks. So I didn't even have to add or remove the quotes from the date command. I removed these double quotes using the sed command, and replaced them with Unix Timestamp values. Thank you so much. – P.Lonnie Jun 23 '21 at 10:29
  • As of today, both answers here presuppose that you have GNU `date` (i.e. Linux). The `date` command on other platforms (MacOS, BSD, AIX, Solaris, etc) lacks the `-d` option. – tripleee Aug 15 '22 at 11:47

2 Answers2

3
$ date -d '1970-01-01T00:00:00Z' +"%s"
0
Roman Pavelka
  • 3,736
  • 2
  • 11
  • 28
0

I note the direction I solved it.

    timestamp=`echo $value | jq '.Datapoints['$i'].Timestamp'`
    #2021-06-23T09:48:00Z

    timestamp=`echo $timestamp | sed 's/\"//g'`
    echo "[$timestamp]"
    utctimestamp=`date -d $timestamp +%s`
P.Lonnie
  • 105
  • 2
  • 11