Web3 Get Block Function – Use a Web3 Get Block Timestamp Operate

How do I get the most recent block in Web3? If this can be a query you have got been asking your self, then you’re precisely the place it’s worthwhile to be! This Web3 tutorial will present you get the present block by timestamp utilizing Moralis. In actual fact, because of Moralis’ EVM API, all it takes is a single name to the ”get_date_to_block” endpoint whereas passing a date and chain as parameters: 

from moralis import evm_api

api_key = "YOUR_API_KEY"

params = {

    "date": "", 

    "chain": "eth", 


end result = evm_api.block.get_date_to_block(




print(end result)

When working with the primary Web3 infrastructure supplier, it doesn’t need to be tougher to get the present block based mostly on a timestamp than the above! If you wish to be taught extra concerning the ”get_date_to_block” endpoint, take a look at Moralis’ get block by date Web3 documentation. 

For a extra detailed breakdown of implement this performance into an app, learn on as we present you the way to take action by an Ethereum Python implementation. What’s extra, keep in mind to register with Moralis when you plan to hitch us all through this tutorial. Signing up is free, and also you want an account to observe alongside! 

Access the Web3 get block feature today - sign up with Moralis


In at present’s Web3 tutorial, we are going to illustrate get any block by constructing a Python software in three steps:

  1. Utilizing a Web3 get block perform – Moralis’ ”get_date_to_block” endpoint
  2. Organising the Web3 get block by timestamp backend
  3. Constructing the Web3 get block frontend 

By the top of this tutorial, you’ll have your personal Python app finalized, enabling you to repeatedly get blocks based mostly on timestamps. If this sounds fascinating and also you wish to get going instantly, click on right here to leap straight into the Web3 get block characteristic tutorial! 

When constructing decentralized purposes (dapps), platforms, and different Web3 tasks, you’ll shortly notice that you simply want entry to on-chain knowledge. For the reason that Web3 business is blockchain-based, you possibly can think about that one piece of such data is block numbers. Getting this knowledge may also help you to, for example, entry transactional knowledge at given instances. Because of this, this Web3 tutorial will present you get a block by a timestamp utilizing Moralis! 

To make this course of as accessible as attainable, we shall be using Moralis’ EVM API and the ”get_date_to_block” endpoint. That is one in all many Web3 APIs provided by Moralis, and if you’re critical about stepping into the area, take into account trying out extra Moralis instruments. For example, a fantastic instance is the Web3 Streams API, permitting you to stream on-chain knowledge into your tasks through Moralis webhooks! 


Right here on the weblog, you may also discover subjects past getting blocks based mostly on timestamps. For example, examine BNB testnet taps or take a look at our information on Web3.py vs Web3.js! 

Now, earlier than you proceed, keep in mind to enroll with Moralis, as it’s worthwhile to have an energetic account to observe alongside. Setting one up is free and solely takes a number of seconds! 

Web3 Get Block Function Tutorial 

Within the subsequent sections, we are going to kickstart this Web3 tutorial illustrating get a block quantity from any chain. Extra particularly, we are going to present you create a Python software enabling you to get the present block based mostly on a timestamp! 

As an example what you can be working in the direction of, you’ll find a print display screen of the app’s touchdown web page down under: 

Web3 get block application landing page

The app options three core components: two enter fields and a ”Get Block” button. To make use of the app, all it’s worthwhile to do is choose a time, date, and chain, adopted by hitting the button. In return, it is best to obtain a response much like the one proven under: 

Response code after using the Get Block button to receive a Web3 get block timestamp

To have the ability to seamlessly get the present Web3 block, we shall be utilizing Moralis’ EVM API and the ”get_date_to_block” endpoint to create this app. If this sounds thrilling, be a part of us as we cowl the whole course of from begin to end! 

When you favor watching movies to be taught, you may also take a look at the clip under from Moralis’ YouTube channel. Within the video, one in all our Web3 builders offers a complete walkthrough of every step:

Now, let’s say you’re uncertain what a Web3 get block characteristic is. If that’s the case, you possibly can learn extra about Moralis’ ”get_date_to_block” endpoint under the third step. In any other case, be a part of us as we begin by protecting the required stipulations within the following sub-section! 


Earlier than diving into this Web3 tutorial on get the present block by timestamp, you will need to have the next prepared: 

  • Set up Moralis – Open a brand new terminal and set up Moralis by working the next command:
pip set up moralis
  • Set up Django and the Relaxation Framework – Run the terminal inputs under to put in Django and Relaxation: 
pip set up django
pip set up djangorestframework django-cors-headers

Step 1: Utilizing a Web3 Get Block Operate – Moralis’ ”get_date_to_block” Endpoint 

On this preliminary step, we are going to present a fast demo of Moralis’ ”get_date_to_block” endpoint. This may present you seamlessly use a Web3 perform to get a block by timestamp!

To get going, begin by establishing a brand new Django Python challenge. Subsequent, create a ”companies.py” file and add the code under: 

from moralis import evm_api

api_key = "YOUR_API_KEY"

params = {

    "date": "", 

    "chain": "eth", 


end result = evm_api.block.get_date_to_block(




print(end result)

From there, it’s worthwhile to configure the code by changing ”YOUR_API_KEY” along with your Moralis API key: 

API key parameter inside the file

You possibly can fetch your key by logging in to the Moralis admin panel and navigating to the ”Web3 APIs” tab: 

Web3 API landing page on the Moralis admin panel

Copy your key and enter it into the code. Lastly, you additionally want so as to add a date to the ”date” parameter. This should be a “Unix date” in milliseconds or a date string. For example, it could actually look one thing like this: ”1667823435”. 

As soon as you’re executed configuring the code, all that continues to be is working the script. To take action, open a brand new terminal, enter ”python companies.py”, and hit enter. This could return a response much like the one proven under. Amongst different issues, the response comprises the variety of the block closest to the timestamp, which is the second parameter: 


  "date": "2020-01-01T00:00:00+00:00",

  "block": 9193266,

  "timestamp": 1577836811,

  "block_timestamp": "2022-01-03T22:59:39.000Z",

  "hash": "0x9b559aef7ea858608c2e554246fe4a24287e7aeeb976848df2b9a2531f4b9171",

  "parent_hash": "0x011d1fc45839de975cc55d758943f9f1d204f80a90eb631f3bf064b80d53e045"


That’s it! Congratulations, you now know to make use of a Web3 perform to get a block by timestamp!

Within the remaining two steps, we are going to present you implement this performance into an software. If this sounds fascinating, be a part of us within the subsequent part as we cowl the backend code! 

Step 2: Setting Up the Web3 Get Block By Timestamp Backend 

To create the Web3 app used to get a block by timestamp, we shall be utilizing an already-developed Python software template. So, the very first thing it’s worthwhile to do is go to the GitHub repository down under and clone the challenge: 

Full Web3 Get Block App Documentation – https://github.com/MoralisWeb3/youtube-tutorials/tree/fundamental/get-block-by-date

With a replica of the challenge in your native listing, allow us to break down the backend code! First, we will go to ”companies.py” to see how the code differs from the preliminary step:

from moralis import evm_api

from dotenv import load_dotenv

import os

api_key = os.getenv("MORALIS_API_KEY")

def get_block_by_date(date, chain):

    params = {

        "date": date,

        "chain": chain,


    end result = evm_api.block.get_date_to_block(




    return end result

The code in ”companies.py” remains to be liable for calling Moralis’ ”get_date_to_block” endpoint. Nonetheless, we modify it by defining the ”get_block_by_date()” perform, making the code extra dynamic. 

The ”get_block_by_date()” perform takes two variables as arguments: ”date” and ”chain”. As such, we will implement logic enabling app customers to specify each these parameters.

We additionally take away the API key from this file, as displaying this worth is a safety threat. As such, it’s worthwhile to arrange a ”.env” file in your listing and create a brand new atmosphere variable: 


Within the snippet above, Don’t forget to exchange ”REPLACE_ME” along with your precise key.

With the ”companies.py” script prepared, we additionally be sure so as to add it to ”views.py”: 

Showing the views.py file and code structure for the Web3 get block endpoint

Lastly, from there, we open the ”urls.py” file and eventually add a brand new path: 

Script for the Web3 get block timestamp function

However, that covers the important components of the backend code! Allow us to transfer on to the third step of this Web3 get block tutorial and look nearer on the frontend! 

Step 3: Constructing the Web3 Get Block Frontend 

The very first thing we do is open the ”package deal.json” file, the place we be sure so as to add ”proxy” and ”axios”: 

Showing the package.json file and the proxy and axios information

Subsequent, allow us to study the code in ”App.js”. Right here, the central perform is ”refreshBlockByDate()”: 

const refreshBlockByDate = async () => {

    await axios


      .then((res) => {



      .catch((err) => console.log(err));


First, we use “axios” to hook up with the backend, enabling us to name the ”get_block” endpoint whereas passing the chain and date as parameters. These two variables are fetched from the app’s UI, permitting customers to pick a series and date. From there, the rest of the code is liable for calculating the Unix time, rendering the response and presenting it to the customers, and so on. 

Lastly, earlier than launching and testing your Web3 get block app, it’s worthwhile to open a brand new terminal, ”cd” into the frontend folder, and set up the “axios” dependencies with the next command:

npm axios

Congratulations! You may have now created a Web3 Python software that may get a block by timestamp! 

When you at any level throughout this Web3 get block tutorial skilled any bother, please take a look at the video firstly of the article, as this can reply any of your questions. You too can take a look at Moralis’ get block by date Web3 documentation, explaining the ”get_date_to_block” endpoint in additional element!

What’s a Web3 Get Block Function? 

As we briefly mentioned within the introduction, you typically want on-chain knowledge when growing dapps and different tasks. One such piece of knowledge is block numbers, which might be advantageous in a number of methods. For example, block numbers may also help you get transaction knowledge at particular closing dates. 

Nonetheless, querying the block quantity at a cut-off date is a difficult activity, which is why builders profit from “Web3 get block” options. A Web3 get block characteristic may also help you to simply fetch any block based mostly on a timestamp, and the most effective different is Moralis’ ”get_date_to_block” endpoint.

When working with Moralis, you solely want a single API name to the ”get_date_to_block” endpoint. By visiting the official get block by date Web3 documentation, you possibly can strive it out your self straight within the browser, and it appears to be like like this: 

Web3 get block documentation page with parameter and code information

All it’s worthwhile to do is enter a series and a date: 

Input fields for the endpoint parameters

From there, you possibly can click on on the ”Strive It” button and obtain a response in return: 

Arrow pointing at the Try It button for the Get Block timestamp endpoint

When you preferred this Web3 get block tutorial and what to take a look at comparable content material, we’ve a few articles only for you. Discover ways to get Ethereum transaction particulars, or learn our ENS resolver tutorial! Additionally, discover implement Supabase authentication or discover ways to use the most effective Polygon Mumbai faucet to execute take a look at transactions earlier than launching on the mainnet!

Abstract – Web3 Get Block Function 

How do you get the most recent block on Ethereum? The reply to this query is Moralis’ EVM API and the ”get_date_to_block” endpoint! Thanks to those growth sources, you possibly can create a Web3 Python software permitting you to get any block in three easy steps: 

  1. Utilizing a Web3 get block perform – Moralis’ ”get_date_to_block” endpoint
  2. Organising the Web3 get block by timestamp backend
  3. Constructing the Web3 get block frontend

On this tutorial, we lined the steps above. Consequently, when you have adopted alongside this far, you now know get any block by a timestamp and implement this performance right into a Web3 app. From right here, now you can use your newly acquired information to implement comparable performance into any future challenge! 

When you loved this Web3 tutorial, take a look at different excellent guides right here on Moralis’ Web3 weblog. For example, take into account studying our NodeJS Telegram bot tutorial or our wonderful information answering the query, ”what’s a Solana pockets?”. Moreover, if you’re new to the business and wish to be taught extra concerning the underlying expertise, the next is the information for you: ”What’s Web3 expertise?”.

Additionally, take into account enrolling in Moralis Academy, as that is the easiest way to grow to be a more adept Web3 developer. The academy gives wonderful blockchain programs on all ranges. As such, it doesn’t matter if you’re new to the area or have prior expertise; Moralis Academy has you lined. For example, take a look at the newbie course on Ethereum fundamentals to kickstart your journey!

Moralis Academy

Lastly, earlier than concluding this text, if you’re critical about turning into a blockchain developer, join with Moralis now. With an account, you possibly can leverage the complete energy of Web3 expertise to construct smarter and sooner!  

Source link

- Advertisement - spot_img

Latest stories

You might also like...