forked from Reinis-FRP/defi-tracking
-
Notifications
You must be signed in to change notification settings - Fork 1
/
block_timestamp.py
executable file
·51 lines (41 loc) · 1.5 KB
/
block_timestamp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/usr/bin/env python3
import time
import datetime
import argparse
from web3 import Web3
from dotenv import load_dotenv
import requests
import os
load_dotenv()
# etherscan.io API:
etherscan_api = "https://api.etherscan.io/api"
# Get API keys from .env file:
etherscan_key = os.environ.get("ETHERSCAN_KEY")
# ETH node API:
eth_node_api = os.environ.get("ETH_NODE_API")
def get_block(timestamp):
API_ENDPOINT = etherscan_api+"?module=block&action=getblocknobytime&closest=before×tamp="+str(timestamp)+"&apikey="+etherscan_key
r = requests.get(url = API_ENDPOINT)
response = r.json()
return int(response["result"])
parser = argparse.ArgumentParser()
parser.add_argument("-t", "--timestamp", type=int, help="get the latest block for this timestamp")
parser.add_argument("-b", "--block", type=int, help="get the block timestamp")
args = parser.parse_args()
# HTTPProvider:
w3 = Web3(Web3.HTTPProvider(eth_node_api))
if args.block:
block = args.block
timestamp = w3.eth.getBlock(block).timestamp
r_timestamp = timestamp
elif args.timestamp:
r_timestamp = args.timestamp
block = get_block(r_timestamp)
timestamp = w3.eth.getBlock(block).timestamp
else:
block = w3.eth.blockNumber
timestamp = w3.eth.getBlock(block).timestamp
r_timestamp = int(time.time())
print('Requested timestamp: %d is %s UTC' % (r_timestamp, datetime.datetime.utcfromtimestamp(r_timestamp)))
print('Block timestamp: %d is %s UTC' % (timestamp, datetime.datetime.utcfromtimestamp(timestamp)))
print('Block number: %d' % (block))