3

I would like to get the block number given a timestamp in unix time using python, something like:

timestamp = 1438270214
block = get_block_number(1438270214)
>>>25
The Dan
  • 143
  • 1
  • 4

1 Answers1

3

You can get the block number by timestamp, using etherscan's API:

https://api.etherscan.io/api?module=block&action=getblocknobytime&timestamp=1578638524&closest=before&apikey=YourApiKeyToken

Take a look at these links to see how this might work in code: 1, 2 and 3.

Rouhollah Joveini
  • 488
  • 1
  • 3
  • 16
  • It worked fine! I also compared it with another I developed that was very slow and the results were very similar but faster – The Dan Mar 08 '22 at 11:55
  • Good to hear that. The speed/efficiency issue might be due to the searching loops. If you are moving backwards from "now", you might rather want to estimate the block number by estimation of the block's timestamp: e.g.: block_timestamp = last_block_number - ((now_timestamp - target_timestamp) / average_minig_time) or something like that. This gives you a very smaller range of blocks to loop-search until you get the desired one. Take a look at this discussion. – Rouhollah Joveini Mar 08 '22 at 12:12