Utility: translate a date range into Steem block numbers

Words
165
Reading
1 min
Listen
Play
8y

Here's a Python program (using the steem-python library) which converts a start and end date into a range of block numbers. I use this to later pull in the full blocks from that time range, for example to look at all conversations in a certain range, like I did here: https://steemit.com/mathematics/@markgritter/steem-tag-covariance

You'll note that all the date comparison is actually string comparison; I didn't bother to parse any dates. The API returns timestamps that use 24-hour time and a YYYY-MM-DDTHH:DD:SS format, so this works out. For example, "2018-06-01" will compare less than any later date, including "2018-06-01T00:00:00", and greater than any previous date such as "2017-12-12T12:12:12".

Also available a GitHub gist: https://gist.github.com/mgritter/b4543a6edbebc1a8cf003b9733ba957d

The method used here is binary search: once to find some point within the desired interval, another based on that to establish the lower bound, and a final search to establish the upper bound.

You can edit the code to specify your own time range, or specify start and end times on the command line.

#!/usr/bin/python3

from steem import Steem
import sys

startTime = "2018-05-01T00:00:00"
endTime = "2018-05-31T23:59:59"

if len( sys.argv ) > 1:
    startTime = sys.argv[1]

if len( sys.argv ) > 2:
    endTime = sys.argv[2]

s = Steem()

lastBlock = s.head_block_number

upperBound = lastBlock
lowerBound = 1
midpoint = None

while lowerBound + 1 < upperBound:
    probe = ( upperBound + lowerBound) // 2
    b = s.get_block_header( probe )
    print( "block", probe, b['timestamp'] )
    if b['timestamp'] < startTime:
        lowerBound = probe
    elif b['timestamp'] > endTime:
        upperBound = probe
    else:
        midpoint = probe
        break

tooLarge = midpoint
while lowerBound + 1 < tooLarge:
    probe = (lowerBound + tooLarge) // 2
    b = s.get_block_header( probe )
    print( "block", probe, b['timestamp'] )
    if b['timestamp'] <= startTime:
        lowerBound = probe
    else:
        tooLarge = probe

tooSmall = midpoint
while tooSmall + 1 < upperBound:
    probe = ( tooSmall + upperBound ) // 2
    b = s.get_block_header( probe )
    print( "block", probe, b['timestamp'] )
    if b['timestamp'] <= endTime:
        tooSmall = probe
    else:
        upperBound = probe

firstBlock = s.get_block_header( lowerBound )
lastBlock = s.get_block_header( upperBound - 1 )

print( "First block:", lowerBound, firstBlock['timestamp'] )
print( "Last block:", upperBound - 1, lastBlock['timestamp'] )
Utility: translate a date range into Steem block numbers | Ecency