What Is a Unix Timestamp?
A Unix timestamp is the number of seconds or milliseconds since 1970-01-01 00:00:00 UTC (the epoch). It is an absolute instant independent of time zone — the same moment yields the same number in Beijing, London, or New York.
Representing time as one integer lets you store, compare, and subtract moments like ordinary numbers, without the complexity of human calendars.
Three easy-to-miss details:
- The epoch was a choice. 1970-01-01 UTC is simply what the early Unix team picked; any other day would work identically.
- It is signed. Times before 1970 are negative:
1969-12-31 23:59:59 UTCis-1, which you meet with birthdates or historical archives. - It is an integer, not a float. Floating-point storage introduces precision error that can break comparisons and sorting.
Precision: Digit Count Determines the Unit
The most common production bug is mixing units. All four precisions exist in real systems:
| Precision | Digits | Example | Common source |
|---|---|---|---|
| Seconds | 10 | 1700000000 |
Linux date +%s, MySQL UNIX_TIMESTAMP(), most backend APIs |
| Milliseconds | 13 | 1700000000000 |
JavaScript Date.now(), Java System.currentTimeMillis() |
| Microseconds | 16 | 1700000000000000 |
Python time.time_ns()//1000, MySQL DATETIME(6) |
| Nanoseconds | 19 | 1700000000000000000 |
Go time.Now().UnixNano(), Python time.time_ns() |
There is one rule: a 13-digit value ÷ 1000 ≈ a 10-digit value. Store 13 digits as seconds and the date jumps tens of thousands of years ahead. A converter should detect precision from the digit count — the timestamp converter does, and renders every major zone at once.
Digit counting has one real blind spot: 16-digit microseconds mistaken for milliseconds, a 1000x error. When crossing system boundaries, encode the unit in the field name (created_at_ms) instead of relying on inference.
Time Zones: An Offset Is Not a Time Zone
A timestamp is an absolute UTC instant. The 2023-11-15 06:13:20 on a page is that instant rendered in your local zone.
const ts = 1700000000 // seconds
const d = new Date(ts * 1000) // note ×1000 to milliseconds
console.log(d.toString()) // local: Wed Nov 15 2023 06:13:20 GMT+0800
console.log(d.toISOString()) // UTC: 2023-11-14T22:13:20.000Z
| Concept | Meaning | Use |
|---|---|---|
| UTC | Coordinated Universal Time, atomic-clock based | The single basis for storage and computation |
| GMT | Greenwich Mean Time, astronomical | Colloquially interchangeable with UTC; docs should say UTC |
| Offset | Difference from UTC in hours, e.g. +08:00 |
Describes one instant only — not a zone |
+08:00 only says this instant is eight hours ahead; China is +08:00 year-round while London is +00:00 in winter and +01:00 in summer. To express "where the user is", use an IANA identifier (Asia/Shanghai, Europe/London): tzdata carries the historical rule changes, an offset does not.
For regional conversion, the time zone converter works from the IANA database and crosses DST transitions correctly.
Always store and transmit in UTC; format for the user's zone only at display time.
DST and Leap Seconds
Regions with daylight saving break the calendar twice a year:
| Scenario | Moment | What happens | Consequence |
|---|---|---|---|
| Spring forward | local 02:00 → 03:00 | 02:00–02:59 does not exist | A job scheduled in that hour silently never runs |
| Fall back | local 03:00 → 02:00 | 02:00–02:59 occurs twice | One local time maps to two instants; logs, de-duplication, aggregation break |
Calendar arithmetic ("add 24 hours", "same time tomorrow") drifts by an hour on transition days. The fix: do arithmetic on the UTC timestamp, then format — never add or subtract on wall-clock time.
Leap seconds are a different deviation: Unix time advances at a fixed 86,400 seconds per day and deliberately ignores them; the OS/NTP compensates underneath, usually by smearing one second across several hours. Most applications never notice; financial matching and satellite timing need explicit handling.
For date spans or adding business days use the date calculator; to confirm when a schedule actually fires use the cron parser — cron runs in the server's local zone, UTC by default in containers.
Storage Formats and Database Types
| Approach | Pros | Cons | Use when |
|---|---|---|---|
| Integer timestamp (s/ms) | Consistent across languages, fast compares, no tz ambiguity | Not human-readable; hard to aggregate by date in SQL | Logs, sorting, cross-system transport |
| ISO 8601 with offset | Readable, lexicographically sortable, self-describing | Longer strings, larger indexes | API responses, config files |
| Native DB temporal type | Group by date, index-friendly, rich functions | Semantics differ per engine; check tz awareness | Business tables needing date aggregation |
| Local-time string | — | No zone, not comparable, not sortable | ❌ Never |
| Database | Type | TZ aware? | Notes |
|---|---|---|---|
| PostgreSQL | timestamptz |
✅ Stores UTC, displays in session tz | Preferred; plain timestamp has no tz — do not mix them up |
| MySQL | DATETIME |
❌ Stored literally | Wall-clock values; agree on UTC when crossing zones |
| MySQL | TIMESTAMP |
✅ Stores UTC, displays in session tz | Range ends 2038-01-19 and starts 1970 |
| SQLite | No native type | ❌ | Usually integer timestamps or ISO 8601 text |
| MongoDB | Date |
✅ UTC milliseconds internally | Drivers convert automatically |
MySQL's TIMESTAMP hitting the 2038 ceiling is a real incident source — use DATETIME holding UTC, or BIGINT, for new tables.
Conversion in Each Language
JavaScript (milliseconds → readable, watch the unit):
const sec = 1700000000
const d = new Date(sec * 1000) // seconds → milliseconds
const iso = d.toISOString() // UTC string, trailing Z
const local = d.toLocaleString('en-US') // local-time string
// Render in a specific zone (required for SSR and multi-zone reports)
new Intl.DateTimeFormat('en-US', {
timeZone: 'America/New_York',
dateStyle: 'full', timeStyle: 'long',
}).format(d)
Python:
from datetime import datetime, timezone
ts = 1700000000
print(datetime.fromtimestamp(ts, tz=timezone.utc)) # be explicit about UTC
print(datetime.fromtimestamp(ts, tz=timezone.utc).isoformat())
Python's
datetime.fromtimestamp(ts)without a tz argument interprets the value in the system's local zone — your laptop and a UTC server disagree. This is the most common time bug found only after deployment.
Go:
import "time"
t := time.Unix(1700000000, 0) // seconds
// milliseconds: time.UnixMilli(ms); microseconds: time.UnixMicro
loc, _ := time.LoadLocation("Asia/Shanghai")
fmt.Println(t.In(loc).Format(time.RFC3339))
Java:
Instant i = Instant.ofEpochSecond(1700000000L); // seconds
Instant j = Instant.ofEpochMilli(1700000000000L); // milliseconds
System.out.println(i.atZone(ZoneId.of("Asia/Shanghai")));
// Use java.time (Java 8+); leave java.util.Date and Calendar behind
PHP:
$dt = (new DateTimeImmutable('@1700000000')) // @ prefix means timestamp, defaults to UTC
->setTimezone(new DateTimeZone('Asia/Shanghai'));
echo $dt->format(DateTimeInterface::RFC3339);
Rust:
use chrono::{DateTime, Utc, TimeZone};
let dt: DateTime<Utc> = Utc.timestamp_opt(1700000000, 0).unwrap();
println!("{}", dt.to_rfc3339());
When the Number Is Wrong, Check These Four
| Symptom | Cause | Fix |
|---|---|---|
| Shows 1970-01-01 | A 0 / null was passed, or parsing failed silently | Raise on parse failure; do not fall back to epoch |
| Jumps tens of thousands of years | Milliseconds treated as seconds | Standardise precision; encode the unit in the field name |
| Correct locally, 8 hours off on the server | Code parses in local time | UTC everywhere; convert only at display |
| Hours off after a DB migration | One side local, the other UTC | Normalise to UTC and backfill history |
Three boundaries belong in tests too: pre-1970 (negative), 2038-01-19 (32-bit overflow), DST transition days and 29 February. Pass the user's zone to the display layer, run schedules in UTC or as "every N seconds", and add a monotonic sequence when second precision collides.
Reproducible Results
from datetime import datetime, timezone
ts = 1745126400
print(datetime.fromtimestamp(ts, tz=timezone.utc).isoformat())
# → 2025-04-20T05:20:00+00:00
The same timestamp "looking different" on two machines almost always means the tz= argument was omitted: Python then silently uses the system local zone. Paste a suspicious value into the timestamp converter; UTC and major zones render side by side, so a unit error and a zone error are easy to tell apart.