The Cardano epoch time

Let's have a look at how to calculate the epoch number from dates.

following the back-to-the-future theme, three dates with time are shown: destination and present time, last time departed.
The time is set to the start of the Cardano blockchain

Every five days a new epoch starts in Cardano and rewards are paid out and delegations become effective, among other bookkeeping stuff.

So it's evident that we need to compute the start of an epoch or find out which is the current counter.

Calculating the current epoch number

The current epoch number can be calculated from the current time in UTC, that is universal time. We subtract the time of the start of the chain, and divide by five days. All this is done with granularity of seconds.

-- let's do it in PostgreSQL 
SELECT TRUNC(
 (  extract(epoch from CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
  - extract(epoch from timestamp with time zone '2017-09-23 21:44:51+00')
 ) / 24 / 3600 / 5, 0)::INTEGER AS current_epoch;

calculate the epoch number in PostgreSQL

-- let's do it in BigQuery 
SELECT CAST(TRUNC(
 (  UNIX_SECONDS(CURRENT_TIMESTAMP())
  - UNIX_SECONDS('2017-09-23 21:44:51+00')
 ) / 24 / 3600 / 5, 0) AS INTEGER) AS current_epoch;

calculate the epoch number in BigQuery

START_TIME=1506203091  # TZ=UTC date --date='@1506203091' shows it
NOW=$(TZ=UTC date '+%s')
echo "epoch: $(( (NOW - START_TIME) / 24 / 3600 / 5 ))"

calculate the epoch number in a UNIX shell like bash

The above calculations can be modified in that they take a defined date and time for which the epoch number is calculated.

Did we just cross the epoch boundary?

We may want to run some calculations when the epoch has just finished. For example, checking on our staking rewards.

# call this script every hour on minute 50
# crontab: 50 * * * *  

NOW=$(TZ=UTC date '+%s')
CHECK=$(( NOW / 24 / 3600 % 5 ))   # don't ask why; it's just right(tm)
if [ ${CHECK} -ne 2 ]; then
    echo "not an epoch boundary today."
    exit 1
fi
HHMM=$(TZ=UTC date '+%H%M')
if [ ${HHMM} -ge "2145" -a ${HHMM} -lt "2200" ]; then
    echo "just reached a new epoch!"
    ./heavy_work.sh
else
    exit 1
fi

fire a script right after the epoch boundary

That's a good start already. When something interesting pops up in the comments, I'll add it here and continue the post. ✌