mogli
mogli

Reputation: 1609

convert date string with hour and minutes to seconds in bash

I have a sample string that contains YYYYMMDDHHMM format. I am trying to convert it into seconds but getting below error.

[vagrant@CentOS-Seven ~]$ export SAMPLE_DATE=201812051147
[vagrant@CentOS-Seven ~]$ echo $SAMPLE_DATE
201812051147
[vagrant@CentOS-Seven ~]$ date -d $SAMPLE_DATE
date: invalid date ‘201812051147’
[vagrant@CentOS-Seven ~]$

Upvotes: 0

Views: 566

Answers (3)

rbrtflr
rbrtflr

Reputation: 11

You can use the "touch" command to assign that date to a file and then print it using "date", try this:

touch -t 201812051147 tmpfile ; date -r tmpfile +%s ; rm -f tmpfile

Upvotes: 0

James Brown
James Brown

Reputation: 37394

Apparently separating date and time parts with a space is enough, so:

$ echo 201812051147 | 
  sed -E 's/(.{8})(.{4})/\1 \2/' | 
  date -f - +"%s"

Output:

1544003220

Upvotes: 1

Socowi
Socowi

Reputation: 27195

According to this answer date has not option to specify the input format. Therefore you have to convert your input into a format that is accepted by date. The sed command in the following command converts 201812051147 to 2018-12-05 11:47.
To convert a date to seconds, use the output format +%s.

$ input=201812051147
$ date -d "$(sed -E 's/(....)(..)(..)(..)(..)/\1-\2-\3 \4:\5/' <<< "$input")" +%s
1544010420

Please not that the output depends on your systems timezone. You can change the timezone by setting the TZ environment variable.

By the way: You don't have to export your variable in this case. Also, the convention for naming variables in bash is to use lowercase letters. By convention only special variables are written in all caps. Using variable names written in all caps could lead to a name collisions with these variables.

Upvotes: 1

Related Questions