Reputation: 51
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.
Upvotes: 0
Views: 275
Reputation: 11
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
Upvotes: 1
Reputation: 47099
Use substring expansion:
$ a="2016-06-13T18:30:31.868Z"
$ echo "${a:11:8}"
18:30:31
Upvotes: 0
Reputation: 246774
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
Upvotes: 2
Reputation: 42007
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'
Upvotes: 1