It's actually possible to use the fact that block-times are locally roughly linearly separated to optimize far beyond a binary search.
This code typically finds the closest block with 3 or 4 calls:
from web3 import Web3, WebsocketProvider
web3 = Web3(WebsocketProvider(f'wss://:{PROJECT_SECRET}@mainnet.infura.io/ws/v3/{PROJECT_ID}'))
T = lambda i_block: web3.eth.getBlock(i_block).timestamp
ilatest = web3.eth.get_block('latest')['number']
def iblock_near(tunix_s, ipre=1, ipost=ilatest, radii=[25000, 1000, 100, 8, 1]):
ipre = max(1, ipre)
ipost = min(ilatest, ipost)
t0, t1 = T(ipre), T(ipost)
av_block_time = (t1 - t0) / (ipost-ipre)
print()
print(f'Searching between blocks {ipre} ({t0}) and {ipost} ({t1})')
# if block-times were evenly-spaced, get expected block number
k = (tunix_s - t0) / (t1-t0)
iexpected = int( ipre + k * (ipost - ipre))
# get the ACTUAL time for that block
texpected = T(iexpected)
off_by_nblocks = abs(int((texpected - tunix_s) / av_block_time))
print(f'target timestamp ({tunix_s}) lies {k:.3f} of the way from block# {ipre} ({t0}) to block# {ipost} ({t1})')
print('Expected block#:', iexpected)
print('Actual timestamp of expected block:', texpected)
print('Off by', off_by_nblocks, 'blocks')
if off_by_nblocks == 0:
print('GOT IT')
else:
return iblock_near(tunix_s, iexpected - off_by_nblocks, iexpected + off_by_nblocks)
Test:
import arrow
tunix_s = arrow.get('2018-06-11T12:34:56').timestamp()
block = iblock_near(tunix_s)
Output: