0

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.

1
  • 1
    Can you show us what you've done so far? Commented Jun 16, 2016 at 19:12

4 Answers 4

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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'

Comments

1

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

Comments

0

Use substring expansion:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.