Unix Timestamp Code Examples
Ready-to-use code snippets for working with Unix timestamps in 12+ languages.
Python
import time
epoch = int(time.time())
print(epoch) # e.g. 1700000000import datetime
ts = 1700000000
dt = datetime.datetime.fromtimestamp(ts, tz=datetime.timezone.utc)
print(dt.strftime('%Y-%m-%d %H:%M:%S UTC')) # 2023-11-14 22:13:20 UTCimport datetime
dt = datetime.datetime(2024, 1, 15, 10, 30, 0, tzinfo=datetime.timezone.utc)
epoch = int(dt.timestamp())
print(epoch) # 1705314600Working with Timestamps in Code
Unix timestamps are supported natively in every mainstream programming language. The patterns are similar: get the current time, convert to/from a date object, and format for display. The key differences are precision (seconds vs milliseconds) and how timezones are handled.
The most important rule: always store and transmit timestamps in UTC. Convert to local time only at the display layer. This avoids DST bugs, makes timestamps sortable as integers, and eliminates timezone ambiguity in stored data.
Language Timestamp Precision Comparison
| Language | Default Unit | Current Time Function |
|---|---|---|
| Python | Seconds (float) | time.time() |
| JavaScript | Milliseconds | Date.now() |
| Go | Nanoseconds | time.Now().Unix() (seconds), .UnixNano() |
| Rust | Seconds + nanos | SystemTime::now().duration_since(UNIX_EPOCH) |
| Java | Milliseconds | Instant.now().toEpochMilli() |
| PHP | Seconds | time() |
| Ruby | Seconds | Time.now.to_i |
| C# | Ticks (100ns) | DateTimeOffset.UtcNow.ToUnixTimeSeconds() |
| Bash | Seconds | date +%s |
| PostgreSQL | Seconds (float) | EXTRACT(EPOCH FROM NOW()) |
| MySQL | Seconds | UNIX_TIMESTAMP() |
Common Gotchas
JavaScript milliseconds vs seconds
Date.now() returns milliseconds. Divide by 1000 to get seconds. When setting JWT claims, always use Math.floor(Date.now() / 1000) — millisecond exp values set tokens to expire 1000× later than intended.
Python timezone-naive datetimes
datetime.now() returns a naive datetime (no timezone info). Use datetime.now(tz=timezone.utc) or datetime.utcnow() to get UTC. Naive datetimes passed to .timestamp() assume local time, which causes bugs when the server timezone differs from UTC.
Go time.Unix() takes seconds, not ms
time.Unix(ts, 0) expects seconds. If you have a millisecond timestamp, use time.UnixMilli(ts) (Go 1.17+) or time.Unix(ts/1000, (ts%1000)*int64(time.Millisecond)).
Database TIMESTAMP vs BIGINT
TIMESTAMP columns in MySQL are limited to 2038-01-19 (32-bit internally). Use DATETIME or BIGINT for timestamps beyond 2038. PostgreSQL's TIMESTAMPTZ is safe — it uses 64-bit internally.
Frequently Asked Questions
What is the best way to store dates in a database?▼
Store as a BIGINT Unix timestamp in seconds (or milliseconds if sub-second precision is needed). This is timezone-independent, sorts correctly as an integer, and works identically across all databases and languages.
How do I convert a Unix timestamp to ISO 8601?▼
In Python: datetime.utcfromtimestamp(ts).isoformat() + "Z". In JavaScript: new Date(ts * 1000).toISOString(). In Go: time.Unix(ts, 0).UTC().Format(time.RFC3339). ISO 8601 format is 2023-11-14T22:13:20Z.
Why should I use UTC instead of local time for storage?▼
Local time is ambiguous during DST transitions (one hour occurs twice). UTC is always unambiguous. Converting between UTC and local time for display is trivial in any language, but converting stored local times after the fact is error-prone.
How do I add days to a timestamp in code?▼
Add seconds directly: new_ts = old_ts + (days * 86400). For months and years, use your language's date library (calendar months have varying lengths). In Python: datetime.fromtimestamp(ts) + timedelta(days=30). In JS: new Date((ts + 86400*30) * 1000).