Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subtract 60 minutes from current time in unix

Tags:

bash

shell

unix

I'm currently creating a shell script that will run a python code once an hour that collects, processes, and displays data from a radar for the previous hour.

The python code I am using requires a UTC begin time and end time in format "YYYYMMDDHHmm". So far, I have found using the unix command date -u +"%Y%m%d%H%M" will retrieve my current time in the correct format, but I have not been able to find a way to subtract 60 minutes from this first time and have it output the "start" time/

code I have tried:

date +"%Y%m%d%H%M-60"  >> out: 201908201833-60

now= date -u +"%Y%m%d%H%M"  >> out:201908201834

echo "$now - 60"  >> out: - 60

I'm just starting to self teach/learn shell coding and I am more comfortable with python coding which is why my attempts are set up more like how you would write with python. I'm sure there is a way to store the variable and have it subtract 60 from the end time, but I have not been able to find a good online source for this (both on here and via Google).

like image 458
MichaelaS Avatar asked Dec 21 '25 04:12

MichaelaS


1 Answers

You can use -d option in date:

date -u +"%Y%m%d%H%M" -d '-60 minutes'

or else subtract 1 hour instead of 60 minutes:

date -u +"%Y%m%d%H%M" -d '-1 hour'

To be able to capture this value in a variable, use command substitution:

now=$(date -u +"%Y%m%d%H%M" -d '-1 hour')

On OSX (BSD) use this date command as -d is not supported:

now=$(date -u -v-1H +"%Y%m%d%H%M")
like image 84
anubhava Avatar answered Dec 24 '25 01:12

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!