Calculate the Number of Seconds Since a Particular Date/Time in SQLite

If you need to calculate the number of seconds that have passed since a given date and time, you can use the UNIXEPOCH() function.

Note that this function was introduced in SQLite 3.38.0, so it will only work if you’re using SQLite 3.38.0 or later.

Example

Here’s an example to demonstrate:

SELECT UNIXEPOCH() - UNIXEPOCH('2020-02-23 07:30:45');

Result:

64254554

In this example, I returned the number of seconds since 2020-02-23 07:30:45.

Obviously, the number of seconds will be different if we run it again later:

SELECT UNIXEPOCH() - UNIXEPOCH('2020-02-23 07:30:45');

Result:

64254823

Number of Seconds since the Start of the Month

Here’s an example that returns the number of seconds that have passed since the start of the current month:

SELECT UNIXEPOCH() - UNIXEPOCH(DATETIME('now', 'start of month'));

Result:

605380

Here, we use the DATETIME() function along with the now argument to return the current date and time. And we also use the start of month modifier to specify the start of the month.

The following example expands on the previous one. It shows the actual dates involved, as well as the seconds between them:

SELECT 
    DATETIME('now', 'start of month') AS "Start of Month",
    DATETIME('now') AS "Now",
    UNIXEPOCH() - UNIXEPOCH(DATETIME('now', 'start of month')) AS "Seconds";

Result:

Start of Month       Now                  Seconds
-------------------  -------------------  -------
2022-03-01 00:00:00  2022-03-08 00:12:04  605524 

You can also use start of day and start of year to return the seconds since the start of the day or year.