Bash: Rounding up unix time to the nearest minute in human readable format

2.2k views Asked by At

I have a list of epoch timestamps like the following:

1481842799,1481842859,.....

So far I managed to use the date command to convert this time in human readable format as follows:

date '+%Y%m%d%H%M%S' -d @1481842799
20161215235959

date '+%Y%m%d%H%M%S' -d @1481842859
20161216000059

or

date '+%Y%m%d%H%M%S' --date='@1481842799'
20161215235959

How can I use the date command to round up such time to the nearest minute as follows?:

20161215235959 to 20161216000000, 20161216000059 to 20161216000100

Tried the following but does not work:

date '+%Y%m%d%H%M%S' --date='@1481842799 + 1 seconds'
date: invalid date `@1481842799 + 1 seconds'
1

There are 1 answers

0
Inian On BEST ANSWER

You are using GNU date, quite evident from the -d flag. If your intention is to increment one second to the EPOCH time, do it as below using the bash arithmetic operator $(())

date '+%Y%m%d%H%M%S' -d "@$((1481842799 + 1))"
20161216043000

Even without incrementing, you can use the double-quotes as

date '+%Y%m%d%H%M%S' -d "@$((1481842799))"
20161216042959

which is pretty much the same as

date '+%Y%m%d%H%M%S' -d @1481842799
20161216042959

As an alternate suggestion, to round up to the nearest minute, you are better off adding 59 and then dividing and multiplying by 60 to truncate that down to the nearest minute, somewhat like chepner's suggestion in the comments.

date '+%Y%m%d%H%M%S' -d "@$(( ((1481842799 + 59) / 60) * 60))"
20161216043000

Adding 59 instead of 60 means that when the original value is already a multiple of 60, it will not be rounded up.