0

I am looking to get a time range from a given time. The start time should be 60 mins before the given time and end time should be 60 mins after the given time.

Purpose: The given time will be like an 'impact time', I am looking to get a suitable range of time around the impact time to be able to grab logs.

Example : Given time is 2018-05-16 20:30:00 This is of the format '%Y-%m-%d %H:%M:%S'

Please help me get: Start time is 2018-05-16 19:30:00 End time is 2018-05-16 21:30:00

This is going to run on a server that will be in PDT/PST always and the date-time is of the format '%Y-%m-%d %H:%M:%S'

  • 1
    Timezones have an effect on time, I’m afraid... – Jeff Schaller May 16 '18 at 23:43
  • @JeffSchaller Sorry for the confusion , This script is going to run on a server that will be in PDT/PST always – Sierra May 16 '18 at 23:56
  • Transitions between PDT and PST affect the time, too. – Jeff Schaller May 17 '18 at 0:02
0

Assuming the timezone is set correctly, and GNU date, you can get the Unix timestamp, subtract, add 60 minutes and convert it back to the format needed:

$ ts=$(date -d "2018-05-16 21:30:00" +%s)  # For BSD date: date -jf "%F %T" "2018-05-16 21:30:00" +%s 
$ echo "$(date -d@$((ts - 3600)) +"%F %T")"
2018-05-16 20:30:00
$ echo "$(date -d@$((ts + 3600)) +"%F %T")"
2018-05-16 22:30:00

... I think this doesn't correctly account for leap seconds and various other problems every programmer should know about time.

  • This does not seem to work, I'm getting some weird year like 1972 ! does this command depend on the linux version ? Mine is Linux meade 3.10.0-693.11.6.el7.x86_64 #1 SMP Thu Dec 28 14:23:39 EST 2017 x86_64 x86_64 x86_64 GNU/Linux and the output i got was : + date -d@-3600 '+%F %T' + sBegindate='1969-12-31 15:00:00' + date -d@3600 '+%F %T' + sEnddate='1969-12-31 17:00:00' + print ' Start date 1969-12-31 15:00:00 and End date 1969-12-31 17:00:00' Start date 1969-12-31 15:00:00 and End date 1969-12-31 17:00:00 – Sierra May 17 '18 at 18:22
  • Uh, why are you doing date -d@-3600 and date -d@3600? 3600 seconds before and after the Unix epoch would of course be around 1970. – Olorin May 18 '18 at 6:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.