Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash round minutes to 5

Tags:

bash

timestamp

We have this string to retrieve date and time in clean format.

 TIMESTAMP=$(date "+%Y%m%d%H%M")

Is there some inline code that we can use to round the minute to 5 down. So if it is 12:03 it will make it 12:00 and if it is 12:49 it will be 12:45

Thank you!

like image 971
user3408380 Avatar asked Apr 01 '14 10:04

user3408380


3 Answers

To do this you can subtract the minutes modulo 5 from the total minutes. To print it out:

echo "$(date "+%Y%m%d%H%M") - ($(date +%M)%5)" | bc

To save it to a variable:

my_var=$(echo "$(date "+%Y%m%d%H%M") - ($(date +%M)%5)" | bc)

This relies on your date format string remaining as it is now - a string of numbers.

Example output:

$ date "+%Y%m%d%H%M"
201404010701
$ echo "$(date "+%Y%m%d%H%M") - ($(date +%M)%5)" | bc
201404010700
like image 153
Josh Jolly Avatar answered Oct 02 '22 00:10

Josh Jolly


A little string manipulation:

case $TIMESTAMP in 
    *[1234]) TIMESTAMP=${TIMESTAMP%?}0;; 
    *[6789]) TIMESTAMP=${TIMESTAMP%?}5;; 
esac

${TIMESTAMP%?} removes the last character. Ref: http://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion

like image 32
glenn jackman Avatar answered Oct 02 '22 01:10

glenn jackman


Not exactly bash only but using dateutils' dround utility, it boils down to:

$ dround now -5m
2014-04-01T10:35:00

or with your format specifiers:

$ dround now -5m -f '%Y%m%d%H%M'
201404011035

Disclaimer: I am the author of that project.

like image 28
hroptatyr Avatar answered Oct 02 '22 00:10

hroptatyr