Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I calculate the difference between two timestamps in SQLite?

I’m struggling to figure out how to correctly calculate the difference in minutes between two timestamps in one of my tables (TIMEIN and TIMEOUT)

Here’s what the table looks like (only 3 rows):

DATE TIMEIN TIMEOUT
2020-05-06 14:00 15:00
2020-05-06 14:45 15:55
2020-05-07 09:00 10:45

This is my current SQL, however it doesn’t output what I want.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SELECT (T.DATE + T.TIMEIN - T.DATE + T.TIMEOUT) AS `Duration`

FROM Transport T;

Here’s my output:

Duration
29
29
19

It should be outputting:
|Duration|
|:——-|
|60 |
|70 |
|105 |

I tried this without using the date, however that lead to an output of -1 for all rows.

>Solution :

Assuming that TIMEOUT is always greater than TIMEIN you can subtract the unix epochs of the 2 values and divide by 60 to get the number of minutes:

SELECT (strftime('%s', TIMEOUT) - strftime('%s', TIMEIN)) / 60 AS Duration
FROM Transport;

See the demo.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading