Search code examples
bashdatetime-formattime-formatstring-to-datetime

Bash scripting: date -d won't accept my string format of hhmmss. I need a workaround


I need a Bash script to accept 1 argument representing a time in hhmmss format, and from that derive a second time 3 minutes before that.

I've been trying to use date -d:

#! /bin/bash
DATE=`date +%Y%m%d`
TIME=$1
NEWTIME=`date -d "$DATE $TIME - 3 minutes" +%H%M%S`
echo $NEWTIME

In action:

$ ./myscript.sh 123456
invalid date `20141022 123456 - 3 minutes'

It seems the problem is with the 6 character time format because 4 characters (eg 1234) works. The subtraction of the 3 minutes is not the problem because I get the same error when I remove it.

It has occurred to me I could parse the time into a more palatable format before sending it to date. I tried inserting delimiters by adding this line:

TIME=${TIME:0:2}:${TIME:2:2}:${TIME:4:2}

It accepted that format but the answer to the - 3 minutes part was inexplicably very wrong (it subtracted 2 hours and 1 minute):

$ ./myscript.sh 123456
103356

Vexing.

It has also occurred to me that I might be able to provide date with an input format, like strptime which I'm familiar with from Python. I've found references to strptime in the context of Bash but I've been unable to get it to do anything.

Does anyone have any suggestions on getting the hhmmss time-string to work? Any help is much appreciated.

FYI: I'm trying to avoid changing the 6 character input format because that would involve changing other scripts as well as getting certain human users to alter long-entrenched habits. I'm also trying to avoid outsourcing this task to another language. (I could easily do this in Python). I want a Bash solution to this problem, if there is one.


Solution

  • TIME=093000
    TIME=${TIME:0:2}:${TIME:2:2}:${TIME:4:2}         # your line
    date -d "2014-10-20 $TIME 3 mins ago" +%H%M%S
    

    Output:

    092700