on unix you should have GNU dates installed. you do not need to deviate from bash. here is the strung out solution considering days, just to show the steps. it can be simplified and extended to full dates.
Watch out! Many of the bash solutions here are broken for date ranges which span the date when daylight savings time begins (where applicable). This is because the $(( math )) construct does a 'floor'/truncation operation on the resulting value, returning only the whole number. Let me illustrate:
DST started March 8th this year in the US, so let's use a date range spanning that:
This should also be leap second safe as long as you always subtract the earlier date from the later one, since leap seconds will only ever add to the difference - truncation effectively rounds down to the correct result.
And in python
on unix you should have GNU dates installed. you do not need to deviate from bash. here is the strung out solution considering days, just to show the steps. it can be simplified and extended to full dates.
For MacOS sierra (maybe from Mac OS X yosemate),
To get epoch time(Seconds from 1970) from a file, and save it to a var:
old_dt=`date -j -r YOUR_FILE "+%s"`
To get epoch time of current time
new_dt=`date -j "+%s"`
To calculate difference of above two epoch time
(( diff = new_dt - old_dt ))
To check if diff is more than 23 days
(( new_dt - old_dt > (23*86400) )) && echo Is more than 23 days
This works for me:
Prints
What is happening?
date -d
to handle time stringsdate %s
to convert time strings to seconds since 1970 (unix epoche)Give this a try:
Watch out! Many of the bash solutions here are broken for date ranges which span the date when daylight savings time begins (where applicable). This is because the $(( math )) construct does a 'floor'/truncation operation on the resulting value, returning only the whole number. Let me illustrate:
DST started March 8th this year in the US, so let's use a date range spanning that:
Let's see what we get with the double parentheses:
Returns '5'.
Doing this using 'bc' with more accuracy gives us a different result:
Returns '5.95' - the missing 0.05 being the lost hour from the DST switchover.
So how should this be done correctly?
I would suggest using this instead:
Here, the 'printf' rounds the more accurate result calculated by 'bc', giving us the correct date range of '6'.
Edit: highlighting the answer in a comment from @hank-schultz below, which I have been using lately:
This should also be leap second safe as long as you always subtract the earlier date from the later one, since leap seconds will only ever add to the difference - truncation effectively rounds down to the correct result.