Get Epoch/Unix Time with the ESP32 (Arduino)

This quick guide shows how to get epoch/unix time using the ESP32 board with Arduino IDE. Getting the epoch time can be useful to timestamp your readings, give unique names to files, and other applications. We’ll request the current epoch time from an NTP server, so the ESP32 needs to have an Internet connection.

Get Epoch Unix Time with the ESP32 Arduino

If you want to get date and time in a human readable format, we recommend the following tutorial instead:

What is epoch time?

The Epoch Time (also know as Unix epoch, Unix time, POSIX time or Unix timestamp) is the number of seconds that have elapsed since January 1, 1970 (midnight UTC/GMT), not counting leap seconds (in ISO 8601: 1970-01-01T00:00:00Z).

NTP (Network Time Protocol)

NTP stands for Network Time Protocol and it is a networking protocol for clock synchronization between computer systems. In other words, it is used to synchronize computer clock times in a network.

ESP32 NTP Network Time Protocol Server How it Works

There are NTP servers like pool.ntp.org that anyone can use to request time as a client. In this case, the ESP32 is an NTP Client that requests time from an NTP Server (pool.ntp.org).

ESP32 Get Epoch/Unix Time Function

To get epoch/unix time with the ESP32, you can use the following function getTime():

// Function that gets current epoch time
unsigned long getTime() {
  time_t now;
  struct tm timeinfo;
  if (!getLocalTime(&timeinfo)) {
    //Serial.println("Failed to obtain time");
    return(0);
  }
  time(&now);
  return now;
}

This function returns the current epoch time. Continue reading for a complete example.

ESP32 Get Epoch/Unix Time Example

Copy the following code to your Arduino IDE. This code connects to the internet and requests the time from an NTP server (pool.ntp.org).

/*
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/epoch-unix-time-esp32-arduino/
  
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.
  
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*/

#include <WiFi.h>
#include "time.h"

// Replace with your network credentials
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

// NTP server to request epoch time
const char* ntpServer = "pool.ntp.org";

// Variable to save current epoch time
unsigned long epochTime; 

// Function that gets current epoch time
unsigned long getTime() {
  time_t now;
  struct tm timeinfo;
  if (!getLocalTime(&timeinfo)) {
    //Serial.println("Failed to obtain time");
    return(0);
  }
  time(&now);
  return now;
}

// Initialize WiFi
void initWiFi() {
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi ..");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print('.');
    delay(1000);
  }
  Serial.println(WiFi.localIP());
}

void setup() {
  Serial.begin(115200);
  initWiFi();
  configTime(0, 0, ntpServer);
}

void loop() {
  epochTime = getTime();
  Serial.print("Epoch Time: ");
  Serial.println(epochTime);
  delay(1000);
}

View raw code

Insert your network credentials in the following variables and the code will work straight away:

// Replace with your network credentials
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

How the Code Works

Let’s take a quick look on how the code works.

Libraries

First, you need to include the WiFi library to connect the ESP32 to your local network; and the time library to handle time structures.

#include <WiFi.h>
#include "time.h"

Network Credentials

Insert your network credentials in the following variables so that the ESP32 can connect to your network.

// Replace with your network credentials
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

NTP Server

We’ll request the time from pool.ntp.org, which is a cluster of timeservers that anyone can use to request the time.

const char* ntpServer = "pool.ntp.org";

getTime() function

The getTime() function gets and returns the current epoch time. If it is not able to get the time, it returns 0.

// Function that gets current epoch time
unsigned long getTime() {
  time_t now;
  struct tm timeinfo;
  if (!getLocalTime(&timeinfo)) {
    //Serial.println("Failed to obtain time");
    return(0);
  }
  time(&now);
  return now;
}

initWiFi()

The initWiFi() function initializes Wi-Fi and connects the ESP32 to your local network.

void initWiFi() {
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi ..");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print('.');
    delay(1000);
  }
  Serial.println(WiFi.localIP());
}

setup()

In the setup(), initialize the Serial Monitor at a baud rate of 115200.

Serial.begin(115200);

Call the initWiFi() function to initialize Wi-Fi:

initWiFi();

Configure the time using the configTime() function. The first and second arguments correspond to the GMT time offset and daylight saving time. However, because we’re interested in getting epoch time, these arguments should be 0. The last argument is the NTP server (ntpServer):

configTime(0, 0, ntpServer);

loop()

In the loop(), get the epoch time and save it in the epochTime variable:

epochTime = getTime();

Finally, print the epoch time every second:

Serial.print("Epoch Time: ");
Serial.println(epochTime);
delay(1000);

Demonstration

Upload the code to your ESP32 board. Then, open the Serial Monitor at a baud rate of 115200. Press the ESP32 on-board RST button. It should connect to Wi-Fi and start printing the current epoch/unix time every second.

ESP32 Get Epoch Unix Time Serial Monitor

Wrapping Up

This was a quick guide showing you how to get epoch/unix time with the ESP32. The epoch time is the number of seconds elapsed since January 1 1970. To get time, we need to connect to an NTP server, so the ESP32 needs to have access to the internet.

If you’re interested in getting date and time in a human readable format, refer to the next tutorial:

We hope you’ve found this tutorial useful. If you want to learn more about the ESP32, check our resources:

Thanks for reading.



Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Enjoyed this project? Stay updated by subscribing our newsletter!

9 thoughts on “Get Epoch/Unix Time with the ESP32 (Arduino)”

  1. Hi, how to change it to milliseconds? I try multiply it by 1000 and it shows wrong time. I do like this, Serial.println(epochTime * 1000);

    Reply
  2. Great site for newbies like me – than you for all the effort.

    I have a question regarding NTP requests: does each call of the function cause network traffic or ist there some „intelligence“ in the system that the internal clock is used for frequent requests and the NTP servers are only called once in a while to synchronise?

    I need the time very frequently but want to avoid permanent network traffic.

    Thanks for consideration,

    Thomas

    Reply
    • I believe that it is the configTime() call that performs the actual ntp query, so we do it once only — in the setup() function. Thereafter, we free-wheel using the time facilities of the ESP32. If accurate time is required, it would make sense to call configTime() periodically, at an interval that is appropriate to compensate for the drift of your ESP32 clock.
      Regards,
      Gerallt.

      Reply
  3. I have tried this code a number of times but in each case I get the “Failed to obtain time” message.
    This code was embedded into the Telegram Bot software which works brilliantly. So the internet access is working OK. Even the stand-alone code fails to work.
    Any suggestions. ?
    Thanks in advance.

    Reply
    • Hi.
      That’s weird.
      I’ve just testes the code now and it is working fine for me.
      What’s the ESP32 add-on version that you’re using? You can check it by going to Tools > Board > Boards Manager and search for ESP32.
      Regards,
      Sara

      Reply
  4. Thanks for the nice sample
    Be aware that in case you set date’s > 20 years from now we error out with: Failed to obtain time 1
    try this one……. setTime(2099,3,28,1,59,50,1);

    void setTime(int yr, int month, int mday, int hr, int minute, int sec, int isDst){
    //struct tm tm;
    timeinfo.tm_year = yr – 1900; // Set date
    timeinfo.tm_mon = month-1;
    timeinfo.tm_mday = mday;
    timeinfo.tm_hour = hr; // Set time
    timeinfo.tm_min = minute;
    timeinfo.tm_sec = sec;
    timeinfo.tm_isdst = isDst; // 1 or 0
    time_t t = mktime(&timeinfo);
    Serial.printf(“Setting time: %s”, asctime(&timeinfo));
    struct timeval AAAAAAAAAnow = { .tv_sec = t };
    settimeofday(&AAAAAAAAAnow, NULL);
    }

    void printLocalTime()
    {
    if(!getLocalTime(&timeinfo)){
    Serial.println(“Failed to obtain time 1”);
    return;
    }
    /*
    timeinfo.x
    tm_sec int seconds after the minute 0-61*
    tm_min int minutes after the hour 0-59
    tm_hour int hours since midnight 0-23
    tm_mday int day of the month 1-31
    tm_mon int months since January 0-11
    tm_year int years since 1900
    tm_wday int days since Sunday 0-6
    tm_yday int days since January 1 0-365
    tm_isdst int Daylight Saving Time flag
    */

    error
    . CONNECTED
    succeeded to connect to NTPServer connection and get the present time
    Seconds: 40
    NTP read: 2023 Apr 19 11:35:40
    Epoch Time: 1681904140
    Date1: 2023-04-19 11:35:40

    lets change the time to the future
    Setting time: Fri Mar 28 01:59:50 2053
    [D][WiFiGeneric.cpp:374] _eventCallback(): Event: 3 – STA_STOP
    [D][WiFiGeneric.cpp:374] _eventCallback(): Event: 3 – STA_STOP
    Failed to obtain time 1
    Failed to obtain time 1
    Failed to obtain time 1
    Failed to obtain time 1
    Failed to obtain time 1

    Reply
  5. Like that guy in the woods somewhere, I’d like to start by saying thank you, Rui and Sara, for your wonderful tutorials.

    This example worked for me until I tried setting a static IP address on the ESP32 as in https://randomnerdtutorials.com/esp32-useful-wi-fi-functions-arduino/#7 . After I added that code to setup(), I get the “Failed to obtain time” error.

    The code I added above setup() was:
    IPAddress local_IP(192, 168, 1, 150);
    IPAddress gateway(192, 168, 1, 1);
    IPAddress subnet(255, 255, 255, 0);

    The code I added in setup(), before configTime() was:
    Serial.println(“Initializing Wi-Fi IP config…”);
    if (!WiFi.config(local_IP, gateway, subnet)) {
    Serial.println(“STA Failed to configure”);
    }

    This code seems to set the IP address as desired, but it breaks something, preventing the time software from working.

    The board I’m using is an Adafruit Feather ESP32 V2. The IDE is Arduino IDE Version 2.1.0. The espressif/arduino-esp32 version is 2.0.9.

    Reply

Leave a Comment

Download Our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.