1. Home
  2. Blog
  3. Software Development

Software Development

Unix Timestamp Explained: Seconds vs Milliseconds, Conversion and 2038

A Unix timestamp is the number of seconds since 1 January 1970 UTC. It is simple, compact and time-zone free, yet unit mix-ups and old 32-bit storage still cause real bugs. Learn how it works, how to convert it in Python, JavaScript and SQL, and what the 2038 problem means, with tested code.

9 min read
Unix timestamp explained: seconds vs milliseconds

Key takeaways

  • A Unix timestamp counts seconds since 1970-01-01 00:00:00 UTC. It is the same number everywhere in the world at a given moment.
  • 10 digits usually means seconds and 13 digits means milliseconds. JavaScript uses milliseconds; Python and most databases use seconds.
  • Always convert with an explicit UTC zone. Local conversions differ between machines.
  • Signed 32-bit storage overflows at 2038-01-19 03:14:07 UTC; the next second wraps to 1901 in our test.

Logs, APIs, JWT tokens, databases and file systems all record time as a single integer like 1794801600. That is a Unix timestamp, also called epoch time or POSIX time. It is the lingua franca of time in computing, because a plain number is easy to store, sort, compare and send. The trouble starts when one system means seconds and another means milliseconds, or when someone converts it in the wrong time zone.

We tested the conversions below with Python 3.13.6, Node.js 24.22.1 and SQLite 3.50.4. A few results were specific to Windows, and we point those out.

What is a Unix timestamp?

It is the number of seconds that have passed since the Unix epoch: midnight UTC on 1 January 1970. The epoch itself is timestamp 0. One day later is 86,400. Times before 1970 are negative. Because it counts from a fixed moment in UTC, a timestamp has no time zone: at any given instant, every computer on Earth agrees on the same number. Time zones only appear when you turn it into a human-readable date.

Why timestamps are so popular

  • Compact: one integer instead of a string with date, time and offset.
  • Unambiguous: no day-first or month-first confusion, no time zone guessing.
  • Easy maths: subtract two timestamps to get elapsed seconds; sorting numbers sorts by time.
  • Universal: every language and database can produce and read one.

A worked example

from datetime import datetime, timezone
print(datetime.fromtimestamp(1794801600, tz=timezone.utc))
# 2026-11-16 04:00:00+00:00
print(datetime(2026, 11, 17, tzinfo=timezone.utc).timestamp())
# 1794873600.0

The difference between those two values is 72,000 seconds, which is 20 hours: from 04:00 on the 16th to midnight on the 17th. Every conversion to a calendar date needs a time zone; here we always used UTC.

A timestamp is the same in every zone. 05:30 on 17 November in India (UTC+5:30) is the same instant as midnight UTC, and Python returned the same number for both:

ist = timezone(timedelta(hours=5, minutes=30))
int(datetime(2026, 11, 17, 5, 30, tzinfo=ist).timestamp())
# 1794873600

Seconds vs milliseconds (and smaller)

This is the number one source of timestamp bugs. Different systems use different units:

Unit Digits today Example Used by
Seconds 10 1794801600 Unix tools, Python time.time(), most SQL, JWT exp
Milliseconds 13 1794801600000 JavaScript Date.now(), Java, many JSON APIs
Microseconds 16 1794801600000000 PostgreSQL internals, some logs
Nanoseconds 19 1794801600000000000 Go, Python time.time_ns()

Our small helper guessed the unit from the digit count and labelled the four example values ['s', 'ms', 'us', 'ns']. The digit rule works for dates between 2001 and 2286, which covers practically all real data. Still, the reliable fix is to name the unit in your API fields, such as created_at_ms.

What happens when you get it wrong? Passing milliseconds to a function expecting seconds produces a date tens of thousands of years in the future. On our Windows machine, Python refused it outright:

datetime.fromtimestamp(1794801600000, tz=timezone.utc)
# OSError: [Errno 22] Invalid argument
datetime.fromtimestamp(1794801600000 / 1000, tz=timezone.utc)
# 2026-11-16 04:00:00+00:00

On Linux the same mistake typically raises a ValueError saying the year is out of range instead; we only tested Windows here, so expect the error type to vary by platform. The opposite mistake is quieter and worse. Passing seconds where JavaScript expects milliseconds gave us a plausible-looking date in 1970:

new Date(1794801600).toISOString()        // 1970-01-21T18:33:21.600Z
new Date(1794801600 * 1000).toISOString() // 2026-11-16T04:00:00.000Z

If you see dates in January 1970 in your app, a seconds value went into a milliseconds field.

Unix timestamps in Python

import time
from datetime import datetime, timezone

time.time()                    # float seconds, e.g. 1794801600.123
int(time.time())               # whole seconds; 10 digits today
time.time_ns()                 # integer nanoseconds

dt = datetime.fromtimestamp(1794801600, tz=timezone.utc)   # timestamp to datetime
ts = int(dt.timestamp())                                    # datetime to timestamp

Always pass tz=timezone.utc to fromtimestamp. Without it you get naive local time, which differs between your laptop, a server and a container. The older utcfromtimestamp() is deprecated; our Python 3.13 run printed a DeprecationWarning for it. Our Python datetime guide covers aware and naive values in depth.

Unix timestamps in JavaScript

Date.now()                                         // milliseconds, 13 digits
Math.floor(Date.now() / 1000)                      // seconds
new Date(1794801600 * 1000).toISOString()          // seconds to Date
Math.floor(Date.parse("2026-11-17T00:00:00Z") / 1000)
// 1794873600

Everything in JavaScript’s Date is milliseconds, so multiply by 1,000 on the way in and divide on the way out. Round down with Math.floor rather than Math.round, so you never produce a timestamp in the future. Our JavaScript Date guide covers parsing and time zones.

Unix timestamps in SQL

SELECT unixepoch('2026-11-16 04:00:00'),        -- 1794801600
       datetime(1794801600, 'unixepoch'),        -- 2026-11-16 04:00:00
       strftime('%s', '2026-11-16 04:00:00');    -- '1794801600'

Those are SQLite functions; all three ran in our test, and note that strftime('%s') returns text. Other databases use different names: UNIX_TIMESTAMP() and FROM_UNIXTIME() in MySQL, EXTRACT(EPOCH FROM ts) and to_timestamp() in PostgreSQL, and DATEDIFF_BIG(SECOND, '1970-01-01', ts) or DATEADD in SQL Server. Our SQL date functions guide lists them side by side.

Dates before 1970

Negative timestamps represent dates before the epoch, but support varies. On Windows, Python refused to convert even one day before 1970:

datetime.fromtimestamp(-86400, tz=timezone.utc)
# OSError: [Errno 22] Invalid argument

EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc)
EPOCH + timedelta(seconds=-86400)
# 1969-12-31 00:00:00+00:00

Adding a timedelta to the epoch works on every platform, because it never calls the operating system’s time functions. Use it whenever historical dates such as birthdays may appear.

Leap seconds: Unix time ignores them

A leap second was added at the end of 2016, so the real gap between 23:59:59 on 31 December 2016 and midnight on 1 January 2017 was two seconds. Unix time pretends every day has exactly 86,400 seconds:

datetime(2017, 1, 1, tzinfo=timezone.utc).timestamp() - \
datetime(2016, 12, 31, 23, 59, 59, tzinfo=timezone.utc).timestamp()
# 1.0

Python reported one second. For almost all applications this simplification is a feature, because it keeps date maths simple. Only scientific and some financial systems need true elapsed time, and they use other time scales.

The year 2038 problem

Many older systems stored timestamps in a signed 32-bit integer. Its maximum value is 2,147,483,647:

datetime.fromtimestamp(2**31 - 1, tz=timezone.utc)
# 2038-01-19 03:14:07+00:00

struct.pack("<i", 2**31)
# struct.error: 'i' format requires -2147483648 <= number <= 2147483647

wrapped = struct.unpack("<i", struct.pack("<I", 2**31))[0]
EPOCH + timedelta(seconds=wrapped)
# 1901-12-13 20:45:52+00:00

One second after 03:14:07 UTC on 19 January 2038, a signed 32-bit counter wraps to its most negative value, which means 13 December 1901. Modern 64-bit systems are safe for billions of years, but 32-bit values still hide in embedded devices, old file formats, database columns defined as INT, and C structures. Audit any timestamp column or field that is 32 bits wide, especially for dates far in the future such as loan end dates or certificate expiry.

Common timestamp bugs

  1. Unit mix-ups between seconds and milliseconds.
  2. Local conversion without an explicit zone, giving different dates on different machines.
  3. Floats losing precision: a float cannot exactly hold nanosecond timestamps; use integers.
  4. Storing as text, which then sorts wrongly if lengths differ.
  5. 32-bit columns that will overflow in 2038.
  6. Comparing expiry times with the wrong unit, so tokens expire at once or never. JWT exp is in seconds, as our JWT guide notes.

Timestamp or datetime column?

For databases, a native timestamp type with time zone support is usually better than a raw integer: it is readable in queries, validated by the database, and works with date functions. Integer timestamps make sense for high-volume event data, cross-system interchange and caches. Whichever you choose, store UTC, document the unit, and convert to local time only in the user interface.

Tip: when debugging, paste a suspicious number into a converter or run datetime.fromtimestamp(x, tz=timezone.utc). A date in 1970 or far in the future almost always means a unit mix-up.

Testing tips

When code handles timestamps, add test cases for the epoch (0), a negative value, a millisecond value passed where seconds are expected, the 2038 boundary (2,147,483,647 and one second later), and a value near midnight UTC that falls on different dates in different zones. Freeze or inject the current time so tests do not depend on when they run, as shown in our Python mocking guide. These few cases catch nearly every timestamp bug we have described.

Final thoughts

A Unix timestamp is the simplest way to record a moment: one integer, the same everywhere. Its pitfalls are just as simple once you know them. Check the unit by its digits, convert with an explicit UTC zone, use timedelta for dates before 1970 on Windows, and make sure nothing stores it in 32 bits. Do that, and timestamps become the most reliable part of your date handling.

FAQ

What is a Unix timestamp?

It is the number of seconds since 1 January 1970 at 00:00 UTC, known as the Unix epoch. It is the same number everywhere in the world at a given moment.

How do I know if a timestamp is in seconds or milliseconds?

Count the digits. Current dates have 10 digits in seconds and 13 in milliseconds. Better still, name the unit in the field or document it in the API.

How do I convert a Unix timestamp to a date in Python?

Call datetime.fromtimestamp with the timestamp and tz set to timezone.utc. Divide by 1000 first if the value is in milliseconds.

What is the year 2038 problem?

Signed 32-bit integers can hold timestamps only up to 19 January 2038 at 03:14:07 UTC. One second later they overflow and wrap to a date in 1901.

Does a Unix timestamp have a time zone?

No. It always counts from midnight UTC on 1 January 1970. Time zones only matter when you convert it into a readable local date and time.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Jaccard Similarity: Formula, Python, MinHash

Jaccard similarity measures overlap between two sets as intersection over union. Work the formula, compute it in Python for words…

Read article →
Software Development

Unix Timestamp Explained: Seconds vs ms

A Unix timestamp counts seconds since 1 January 1970 UTC. Learn seconds vs milliseconds, converting in Python, JavaScript and SQL,…

Read article →
DevOps

Git Hooks: Pre-commit and Commit-msg Examples

Git hooks run scripts at key moments such as commit and push. See tested pre-commit, commit-msg and prepare-commit-msg hooks, sharing…

Read article →
Test Automation

API Testing in Python: Pytest + Requests Suite

Build an API testing suite in Python with pytest and requests: fixtures, status codes, headers, JSON schema validation, CRUD flows,…

Read article →
Software Testing

Test Design Techniques: 9 Methods + Examples

Test design techniques help you write fewer tests that catch more bugs. Learn 9 black-box, white-box and experience-based methods with…

Read article →
Databases & SQL

SQL Temporary Table: Create, Use and Drop It

SQL temporary tables store interim results for one session. Learn syntax for SQL Server, PostgreSQL, MySQL, Oracle and SQLite, session…

Read article →
Databases & SQL

SQL CROSS JOIN: Every Combination + Examples

SQL CROSS JOIN returns every combination of rows from two tables. See the row math, product variants, calendar grids that…

Read article →
Software Development

JavaScript Date: Format, Parse, Timezone Bugs

JavaScript Date explained with tested Node.js code: zero-based months, the date-only UTC parsing trap, toISOString, getTimezoneOffset, Intl formatting, date math…

Read article →
Software Development

Python Requests: GET, POST, Timeouts, Retries

Python requests explained with code tested against a local API: GET with params, POST json vs data, headers and auth,…

Read article →
Software Development

Python Deepcopy vs Copy: Fix Nested Lists

Python deepcopy vs shallow copy explained with tested code: aliasing, nested lists, the [[0]*3]*3 trap, memo and cycles, custom __deepcopy__,…

Read article →
Artificial Intelligence

TF-IDF Explained: Formula and Worked Example

TF-IDF scores a word by how often it appears in a document and how rare it is across all documents….

Read article →
Software Development

Base64 Encoding Explained, With Python Code

Base64 encoding turns bytes into 64 safe text characters. See the bit-level steps, padding, URL-safe base64, the 33% size cost,…

Read article →
DevOps

Git Tag: Create, Push and Delete Release Tags

Git tag explained with tested commands: annotated vs lightweight tags, listing and sorting, pushing with follow-tags, deleting local and remote…

Read article →
Test Automation

Pytest Coverage: pytest-cov and Branch Gaps

Measure pytest coverage with pytest-cov: term-missing reports, branch coverage, HTML reports, pyproject settings and a fail-under gate for CI, with…

Read article →
Software Testing

Error Guessing in Testing: Checklist + Demo

Error guessing uses tester experience to predict where code breaks. Get a ready checklist of risky inputs, a step by…

Read article →
Databases & SQL

SQL LAG and LEAD: Compare Rows, 5 Examples

SQL LAG and LEAD read values from the previous or next row without a self join. Five tested examples: change,…

Read article →
Databases & SQL

SQL STRING_AGG: Combine Rows Into One String

SQL STRING_AGG joins values from many rows into one string per group. See syntax for PostgreSQL, SQL Server, MySQL GROUP_CONCAT,…

Read article →
Software Development

JavaScript Classes: Private Fields and Extends

JavaScript classes explained with tested Node.js code: constructors, methods, #private fields, getters, static members, extends and super, plus the errors…

Read article →
Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →
Software Testing

Positive vs Negative Testing: Differences, 24 Real Test Cases and a Checklist

Positive vs negative testing explained with a real signup form: 6 positive and 18 negative test cases run in pytest,…

Read article →
Databases & SQL

SQL ORDER BY Multiple Columns: ASC, DESC, NULLS LAST, Case and Custom Order

SQL ORDER BY with multiple columns explained with tested queries: mixed ASC and DESC, tie-breakers, NULLS FIRST and LAST, case-insensitive…

Read article →
Databases & SQL

SQL Running Total: SUM OVER, Per-Group Totals, Moving Sums and the RANGE Trap

How to calculate a SQL running total with SUM() OVER: per-group totals, daily cumulative sums, moving sums, percent of total,…

Read article →
Artificial Intelligence

Cosine Similarity Explained: Formula, Worked Example and Python Code

Cosine similarity explained simply: the formula, a worked example by hand, pure Python and NumPy code, cosine vs Euclidean distance…

Read article →
DevOps

Git Squash Commits: 4 Easy Ways, Tested Step by Step (rebase -i, reset, merge)

Git squash commits explained with 4 tested methods: interactive rebase, reset –soft, merge –squash and fixup with autosquash. Before-and-after logs,…

Read article →
Test Automation

pytest parametrize Explained: 7 Patterns with Tested Examples

pytest parametrize explained with 7 tested patterns: basic cases, readable ids, stacked decorators, pytest.param with xfail and skip, indirect fixtures…

Read article →
Software Testing

Retesting vs Regression Testing: 8 Key Differences with a Real Bug Fix Example

Retesting vs regression testing explained with a real bug fix run in pytest: retesting confirmed the fix, the regression run…

Read article →
Artificial Intelligence

RAG Chunking Strategies Explained: Fixed, Overlap, Sentence, Recursive and Headings, Measured

RAG chunking strategies compared on one document with tiktoken 0.14: fixed-size, overlap, sentence packing, recursive splitting and heading-based chunks, measuring…

Read article →
DevOps

Git Stash Explained: Save, Apply, Pop and Untracked Files, Tested

Git stash explained with commands we ran on Git 2.56: push with a message, untracked files, list and show, apply…

Read article →
Software Testing

Pairwise Testing Explained: How All-Pairs Cuts 216 Tests to 13, Tested

Pairwise testing explained with a generator we ran in Python 3.13: a checkout with 216 combinations covered by 13 tests,…

Read article →
Test Automation

Test Doubles Explained: Dummy, Stub, Spy, Mock and Fake, with Tested Python Code

Test doubles explained with one Python example run in pytest 9.2: dummy, stub, spy, mock and fake, when to use…

Read article →
Artificial Intelligence

LLM Context Window Explained: Tokens, Limits and How to Fit More, Measured

The LLM context window explained with token counts we measured using tiktoken: words vs tokens for prose, code and Hindi,…

Read article →
DevOps

Git Cherry-Pick Explained: Copy the Commit You Need, Safely, Tested

Git cherry-pick explained with commands we ran in Git 2.56: copying a hotfix to a release branch, new hashes and…

Read article →
Test Automation

Snapshot Testing Explained: How It Works, When It Helps and When It Hurts

Snapshot testing explained with a pytest and syrupy demo we ran: creating snapshots, reading the diff after a code change,…

Read article →
Software Testing

Mutation Testing Explained: Why 100% Coverage Still Missed Our Bug

Mutation testing explained with a small mutation tool we built and ran: 14 mutants, a test suite with 100% line…

Read article →