Unix Timestamps in Python, JavaScript, and Go
How to generate and format Unix timestamps across JavaScript, Python, and Go, plus common pitfalls like milliseconds vs seconds.
The Milliseconds Trap in JavaScript
In JavaScript and Node.js, `Date.now()` and `new Date().getTime()` return timestamps in milliseconds (13 digits), whereas Unix standard counts seconds (10 digits).
To get a standard 10-digit Unix timestamp in JavaScript: `const timestamp = Math.floor(Date.now() / 1000);`.
Passing a 10-digit second timestamp directly to `new Date(ts)` causes JavaScript to treat it as milliseconds, resulting in a date in January 1970. Always multiply by 1000 first: `new Date(ts * 1000)`.
Python 3: time.time() vs datetime.fromtimestamp()
In Python, obtaining the current timestamp in seconds is straightforward with `time.time()`, which returns a float:
`import time; ts = int(time.time())`
When parsing timestamps back to datetimes, always use timezone-aware methods to prevent naive local time bugs: `from datetime import datetime, timezone; dt = datetime.fromtimestamp(ts, tz=timezone.utc)`.
Go (Golang): time.Now().Unix()
Go provides explicit, type-safe standard library helpers for Unix time:
Get current seconds: `nowSeconds := time.Now().Unix()`
Get current milliseconds: `nowMillis := time.Now().UnixMilli()`
Convert timestamp to time.Time: `t := time.Unix(sec, nsec)`.
Safe Database Storage & 64-Bit Integers
Always store Unix timestamps in signed 64-bit integers (`BIGINT` in PostgreSQL/MySQL). Storing timestamps in 32-bit integers will overflow on January 19, 2038 (the Year 2038 Problem).
64-bit integer timestamps guarantee your database will handle timestamps accurately for hundreds of billions of years.