date difference
time calculation
seconds between dates
date comparison
programming tutorial

How do I check the difference, in seconds, between two dates?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

To get the difference between two dates in seconds, the general pattern is always the same: parse or construct both dates, subtract them, and convert the resulting duration to seconds. The exact API changes by language, but the main complications are time zones, date parsing, and whether you want whole seconds or fractional seconds.

Python Example

In Python, subtracting two datetime values gives a timedelta, and total_seconds() converts that duration into seconds.

python
1from datetime import datetime
2
3start = datetime.fromisoformat("2025-09-23T10:00:00")
4end = datetime.fromisoformat("2025-09-23T10:05:30")
5
6seconds = (end - start).total_seconds()
7print(seconds)  # 330.0

If you want an integer:

python
whole_seconds = int((end - start).total_seconds())
print(whole_seconds)  # 330

This is the most common and reliable Python approach.

JavaScript Example

In JavaScript, subtracting two Date objects gives the difference in milliseconds, so divide by 1000 to get seconds:

javascript
1const start = new Date("2025-09-23T10:00:00Z");
2const end = new Date("2025-09-23T10:05:30Z");
3
4const seconds = (end - start) / 1000;
5console.log(seconds); // 330

Because the result is based on milliseconds, this naturally supports fractional seconds too if the timestamps include them.

SQL Example

In SQL, the exact function depends on the database system. In PostgreSQL, subtracting timestamps gives an interval, and you can convert that to seconds:

sql
1SELECT EXTRACT(EPOCH FROM (
2    TIMESTAMP '2025-09-23 10:05:30' -
3    TIMESTAMP '2025-09-23 10:00:00'
4)) AS seconds;

In MySQL, TIMESTAMPDIFF is the common choice:

sql
1SELECT TIMESTAMPDIFF(
2    SECOND,
3    '2025-09-23 10:00:00',
4    '2025-09-23 10:05:30'
5) AS seconds;

These functions are clearer than trying to manually subtract string values.

What About Time Zones

Time zone handling is where date-difference bugs usually come from. Two timestamps that look close together in local time may represent different instants if one is in UTC and the other is local time.

For example, in Python:

python
1from datetime import datetime, timezone
2
3start = datetime(2025, 9, 23, 10, 0, 0, tzinfo=timezone.utc)
4end = datetime(2025, 9, 23, 10, 5, 30, tzinfo=timezone.utc)
5
6print((end - start).total_seconds())

The important rule is consistency:

  • compare two timezone-aware values in the same frame of reference
  • or compare two naive values only when they truly represent the same local time system

Mixing aware and naive datetimes usually leads to incorrect results or explicit errors.

Whole Seconds vs Fractional Seconds

Some APIs return floating-point seconds, while others return whole numbers. Decide which one you need before converting.

For example, if sub-second precision matters in Python:

python
1from datetime import datetime
2
3start = datetime.fromisoformat("2025-09-23T10:00:00.250000")
4end = datetime.fromisoformat("2025-09-23T10:00:01.750000")
5
6print((end - start).total_seconds())  # 1.5

If you convert too early with int, you lose the fraction.

Negative Differences

Date subtraction can produce negative values when the earlier and later timestamps are reversed.

python
seconds = (start - end).total_seconds()
print(seconds)  # -330.0

If you always want the absolute gap regardless of order:

python
gap = abs((end - start).total_seconds())
print(gap)

That is often useful in elapsed-time comparisons, but not always correct for business logic that cares about ordering.

Common Pitfalls

The biggest pitfall is comparing strings instead of parsed date objects. Date arithmetic should happen on real date or time types, not on formatted text.

Another common issue is forgetting that JavaScript Date subtraction returns milliseconds, not seconds. Division by 1000 is required.

Time zones also cause subtle bugs. A local timestamp and a UTC timestamp may not be directly comparable in the way you expect unless you normalize them first.

Finally, decide whether you need whole seconds or fractional seconds. Truncating too early can silently lose precision.

Summary

  • Parse both dates into real date or time objects first.
  • Subtract the two values to get a duration, then convert that duration to seconds.
  • Python uses timedelta.total_seconds().
  • JavaScript Date subtraction returns milliseconds, so divide by 1000.
  • Handle time zones and fractional-second precision deliberately to avoid subtle errors.

Course illustration
Course illustration

All Rights Reserved.