Unix Timestamp Giải Thích

What Is a Unix Timestamp?

A Unix timestamp (also called POSIX time or Epoch time) is a single integer representing the number of seconds that have elapsed since 00:00:00 UTC on Thursday, January 1, 1970 — a reference point known as the Unix Epoch. For example, the timestamp 1700000000 corresponds to November 14, 2023, 22:13:20 UTC.

Why 1970?

Unix-like operating systems were developed in the late 1960s and early 1970s. The year 1970 was chosen as a convenient, round starting point that was close to the origin of Unix itself. It had no special astronomical or political significance — it was simply practical.

Key Properties

  • Always UTC: Unix timestamps are timezone-agnostic. They always refer to UTC, regardless of where the server or client is located.
  • Integer or float: Whole seconds use a plain integer. Sub-second precision uses a float (e.g., 1700000000.456).
  • Millisecond variants: JavaScript's Date.now() returns milliseconds since epoch, not seconds — always check units.
  • No leap second awareness: The Unix timescale ignores leap seconds, which means it can drift from real UTC by a small amount around leap second events.

Getting the Current Timestamp

Every major programming language provides a built-in way to read the current Unix timestamp:

# Python
import time
print(int(time.time()))          # e.g. 1700000000

# JavaScript
console.log(Date.now())          // milliseconds — divide by 1000 for seconds
console.log(Math.floor(Date.now() / 1000))

# Bash
date +%s

# SQL (PostgreSQL)
SELECT EXTRACT(EPOCH FROM NOW())::BIGINT;

Converting a Timestamp to a Human-Readable Date

# Python
from datetime import datetime, timezone
dt = datetime.fromtimestamp(1700000000, tz=timezone.utc)
print(dt.isoformat())   # 2023-11-14T22:13:20+00:00

# JavaScript
new Date(1700000000 * 1000).toISOString()
// "2023-11-14T22:13:20.000Z"

Common Pitfalls

  • Milliseconds vs seconds: Always confirm whether an API returns ms or s. Dividing by 1000 when unnecessary produces dates in 1970.
  • 32-bit overflow: On systems using a signed 32-bit integer, timestamps will overflow in 2038. See the Year 2038 Problem guide.
  • Negative timestamps: Dates before 1970 are represented as negative integers, which most modern languages handle correctly.

When to Use Unix Timestamps

Unix timestamps are ideal for storing and comparing dates in databases, APIs, and logs. They are compact, sortable, timezone-neutral, and unambiguous. For display to users, always convert to a local datetime with proper timezone handling.