简体   繁体   中英

How to convert this timestamp string into this format in bash script?

I have a csv file I am reading which contains various time stamps of the format "2016-06-13T18:30:31.868Z". I would like to know how ,using bash script, how to convert the string into "18:30:31" leaving only the time component.

Thanks.

You can do this just with bash parameter expansion

datetime="2016-06-13T18:30:31.868Z"
no_date=${datetime #*T}               # remove "2016-06-13T"
timestamp=${no_date%.*}               # remove ".868Z"

or with a regular expression:

if [[ $datetime =~ ([0-9][0-9]:[0-9][0-9]:[0-9][0-9]) ]]; then
    timestamp=${BASH_REMATCH[1]}
fi

It would be better to manipulate date-time with a tool that understands it rather than any text-processing tool.

With GNU date , you can pass the time format and get the output in desired HH:MM:SS format with the %T identifier:

date -d '2016-06-13T18:30:31.868Z' '+%T'

To set a specific timezone, use TZ environment variable:

TZ=EST date -d '2016-06-13T18:30:31.868Z' '+%T'

In Bash

VAR="2016-06-13T18:30:31.868Z"

FRONT_REMOVED=${VAR%.*}

BACK_REMOVED=${FRONT_REMOVED#T*}

Back Removed should be what you want %.* deletes everything after the period

#T* deletes everything before the T

Use substring expansion :

$ a="2016-06-13T18:30:31.868Z"
$ echo "${a:11:8}"
18:30:31

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM