Best way to compare Timestamps in Linux shell/bash script? [duplicate] - bash

This question already has answers here:
Bash script compare two date variables [duplicate]
(5 answers)
Closed 1 year ago.
I have to read a epoch timestamp (in seconds) from a directory /usr/local/healthcheck.txt on my Red Hate Enterprise Linux machine every ~10 minutes (polling). I need perform a comparison on the time to check if the timestamp in the healthcheck.txt file is OLDER than 50 minutes from the current time/timestamp OR if the healthcheck.txt is non-existent, to throw an error. The timestamp in the healthcheck.txt file generally looks like this (its in seconds, as stated above) :
1591783065
I was using date -d #1591783065 to convert the timestamp to Human Readable and get something like this:
Tue Jun 9 16:22:57 UTC 2020
What would be the best approach to compare the current timestamp to this timestamp in the file and check if its older than 50 minutes?
In Java , we have a Date package , and can just use compareTo to compare the times/dates, is there a simple way to do this with shell/bash scripts?

Why don't you stick with epoch-time? You can get the current time as seconds since epoch by
date +%s, so you just have to compare
if (( (healthcheck_time + 50*60) < $(date +%s) ))
then
# .... healthcheck older than 50 minutes
fi

Related

Time since the systemd service was started - Bash [duplicate]

This question already has answers here:
How can I calculate time elapsed in a Bash script?
(20 answers)
Closed 10 months ago.
I want to know the time duration since a systemd service was started, using the --property=ActiveEnterTimestamp i can see the time it has started, and i would like to compare it with current time and get a value in seconds or minutes, how can i achieve this with bash
If i use this solution i am getting a string, but i cannot actually get any time object to make the decision, any help on this would be appreciated.
You could use GNU date to convert the ActiveEnterTimestamp value to seconds-since-the-epoch, then subtract the current seconds-since-the-epoch to get the running time in seconds.
servicestartsec=$(date -d "$(systemctl show --property=ActiveEnterTimestamp your-service-here | cut -d= -f2)" +%s)
serviceelapsedsec=$(( $(date +%s) - servicestartsec))
Substitute "your-service-here" for your actual service name.
The first line assigns the start time in seconds by extracting the date portion of systemctl show --property=ActiveEnterTimestamp... (using cut to extract the second =-delimited field) and then passing it to GNU date and asking for output in seconds-since-the-epoch.
The second line simply subtracts that start time from the current time to get an elapsed time in seconds. Divide that as needed to get elapsed minutes, hours, etc.

How to find 30 days older epoch time in ms from current time in shell script?

How do I find epoch time of 30 days from current time in shell script? If my current time is X in epoch milliseconds.Then I need epoch milliseconds of 30 days older in shell script
#!/bin/sh
current=$(date +'%s%3N')
echo $current
oldtimestamp=$((current - 30*24*60*60))
echo "old is $oldtimestamp"
This doesnt seem to give 30 days old epoch ms. Please let me know how to get it. Thanks in advance
The date command supports some natural language expressions:
date +'%s%3N' --date='30 days ago'
Of course, this will be some milliseconds off when compared to ${current} because of the time it takes to execute these commands themselves, but perhaps it's close enough for you.
Otherwise, the correct arithmetic expression is what Jonathan Leffler wrote:
oldtimestamp=$((current - 30*24*60*60*1000))
but note that things like leap seconds may throw you off in that approach.

How can I get the timestamp in days in awk?

I have a file "file_XYZ_18548".
Here the name's ending 18548 is a timestamp in days, and it is changing day by day, like "file_XYZ_18550".
I would like to get this date via variable but I couldn't find a date command to get the timestamp in days.
I can get the date result but I can't get the timestamp in reverse.
timeinday=18550
timestp=timeinday*86400
datetm=$(echo $timestp | gawk '{print(strftime("%Y-%m-%d %H:%M:%S", $0))}')
echo $datetm
2020-10-14 10:09:10
How can I get this with date command in bash scripting? Is there any way of this via awk/gawk etc..?
Given that 2020-10-14 - 18548 days corresponds to 1970-01-03, it is reasonable to guess that the 'epoch' for the day count is 1970-01-01. It is likely that day 1 was 1970-01-01, so day zero was 1969-12-31.
Converting day count to date
You can use the GNU date command like this:
daycount=18548
date -u -d "#$(( ($daycount-1) * 86400 ))" +"%Y-%m-%d %H:%M:%S"
That yields the result 2020-10-12 00:00:00. You can drop the time component of the format if you wish (you probably do; midnight isn't very exciting when it is always midnight). You can calibrate the -1 to resolve exactly what day should correspond to 18548. Just in case it isn't obvious, there are 86,400 seconds in a day (24 hours • 60 minutes per hour • 60 seconds per minute).
The $(( … )) notation is Bash's Arithmetic Expansion notation.
Converting current time to day count
If you want to convert the current time to the day offset, then you can use the %s specifier to get the seconds since 1970-01-01 00:00:00Z and divide by 86400 to get the number of days:
echo $(( $(date +'%s') / 86400 ))
which (at 2020-10-14 23:30 -06:00, aka 1602739800 seconds since the Unix Epoch) yields the result:
18550
Again, if need be, you can adjust the value of the division to account for when day 1 was in this scheme. Shell arithmetic in Bash is integer arithmetic, which is exactly what is wanted. You might need to use -u to get UTC as the time zone (as I did earlier), and so on.

UNIX Shell Calculate hours difference between two timestamps

I have two timestamps in formats :
Timestamp 1 (Variable - RunStartDate): Thu May 3 14:12:54 CDT 2018
Timestamp 2 (Variable - RunEndDate): Thu May 3 18:11:46 CDT 2018
I want the difference of number of hours between these two timestamps in UNIX shell. (I.e. RunEndDate - RunStartDate in hours)
Please help, I am new to UNIX and it is throwing me errors when I just try to subtract the two.
You have a few options here, such as calling out to Perl or Python and using a date/time library to do the math for you. Another option is to use the date program to convert the dates to seconds, subtract the values, and then convert back to hours. Unfortunately, you can't do floating-point math in Bash, so we'll have to call out to a helper program to do that, too.
START=$(date -d "$RunStartDate" +"%s")
END=$(date -d "$RunEndDate" +"%s")
HOURS=$(bc -l <<< "($END - $START) / 3600")
Note that this will only work on GNU systems (e.g. Linux).

Time calculation in bash

We have a little issue with a time calculation in Bash.
Lets give you a little explaination about the situation up here.
We download every 5 minutes one file from an FTP server. This file contains time information about the data in this file. But the timeformat of the file is in UTC, and our local time is UTC+2. The files contains information about the past 5 minutes from local time. Now we have the following code:
TIMESTAMP=$(echo "$(TZ=UTC date "+%Y%m%d%H%M") - ($(date +%M)%5)-5" | bc)
That works well for several hours but after 55 minutes it becomes a problem. So we dont able to get the files with the 55 minutes, 60 minutes.
So if local time is: 19:47
The file with time 17:40 (utc) is available on the server at 19:45 local time
The time the files are available on the server are not constant too bad...
19:00, 19:05, 19:10 etc... but sometimes the file is one minute later....
This is my crontab file:
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/home/kbroeren/cronscripts
*/1 * * * * /home/kbroeren/cronscripts/radar >> /home/kbroeren/radar_log.txt 2>&1
*/5 * * * * sudo /usr/bin/python /home/kbroeren/cronscripts/radar_plot.py >>/home/kbroeren/out.txt 2>&1
Is there a better and correct way to do this ?
You seem to be looking for %s:
date +%s
This returns:
%s seconds since 1970-01-01 00:00:00 UTC
You'd need to change the arithmetic a bit, though.
The date command can convert to and from a number of date and time formats. If you want to do arithmetic with dates and times, it's probably easiest to convert to “seconds since the unix epoch”, do the arithmetic, and convert back to the time format of your choice.
You might consider something like:
date --date="#$(echo $(TZ=UTC date +%s) - $(date +%s)'%(5*60)-(5*60)' | bc)"

Resources