SMT

Unix Timestamp Code Examples

Ready-to-use code snippets for working with Unix timestamps in 12+ languages.

Python

Get current epoch
import time
epoch = int(time.time())
print(epoch)  # e.g. 1700000000
Epoch → human date
import 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 UTC
Human date → epoch
import datetime
dt = datetime.datetime(2024, 1, 15, 10, 30, 0, tzinfo=datetime.timezone.utc)
epoch = int(dt.timestamp())
print(epoch)  # 1705314600

Working 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

LanguageDefault UnitCurrent Time Function
PythonSeconds (float)time.time()
JavaScriptMillisecondsDate.now()
GoSecondstime.Now().Unix() — .UnixMilli() / .UnixNano() for sub-second
RustSeconds + nanosSystemTime::now().duration_since(UNIX_EPOCH)
JavaMillisecondsInstant.now().toEpochMilli()
PHPSecondstime()
RubySecondsTime.now.to_i
C#SecondsDateTimeOffset.UtcNow.ToUnixTimeSeconds()
BashSecondsdate +%s
PostgreSQLSeconds (float)EXTRACT(EPOCH FROM NOW())
MySQLSecondsUNIX_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)).

C# DateTime vs DateTimeOffset

new DateTimeOffset(DateTime.Parse("2024-01-15T10:30:00Z")) can silently apply the local timezone if the DateTime Kind is Unspecified. Always parse into DateTimeOffset directly: DateTimeOffset.Parse("2024-01-15T10:30:00Z").ToUnixTimeSeconds(). This guarantees UTC is respected.

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 epoch time?

Epoch time (also called Unix time or POSIX time) is the number of seconds elapsed since January 1, 1970, 00:00:00 UTC. It is a timezone-independent integer, which makes it the standard way to store, compare, and transmit timestamps in software. A 10-digit number is seconds; 13 digits is milliseconds.

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.fromtimestamp(ts, tz=timezone.utc).isoformat() — note: utcfromtimestamp() is deprecated since Python 3.12. In JavaScript: new Date(ts * 1000).toISOString(). In Go: time.Unix(ts, 0).UTC().Format(time.RFC3339). Result format: 2023-11-14T22:13:20+00:00.

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).

Java Epoch Time

Epoch time — also called Unix time or POSIX time — is the number of seconds elapsed since January 1, 1970 at 00:00:00 UTC. Java provides first-class support for epoch time through the java.time API introduced in Java 8.

The reference point (the "epoch") gives computers a shared zero from which to measure time intervals. Because it is a single integer independent of timezone, epoch time is simple to store, sort, and compare across distributed systems.

How to get epoch time in Java

Use Instant.now().toEpochMilli() to get the current time in milliseconds, or Instant.now().getEpochSecond() for seconds. To convert back to a human-readable date, attach a ZoneId:

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

// 1. Get current epoch (seconds and milliseconds)
long epochSec = Instant.now().getEpochSecond();   // e.g. 1700000000
long epochMs  = Instant.now().toEpochMilli();     // e.g. 1700000000000

// 2. Epoch → human date in UTC
ZonedDateTime utc = Instant.ofEpochSecond(1700000000L).atZone(ZoneId.of("UTC"));
System.out.println(utc.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
// 2023-11-14T22:13:20Z

// 3. Epoch → human date in a specific timezone
ZonedDateTime india = Instant.ofEpochSecond(1700000000L).atZone(ZoneId.of("Asia/Kolkata"));
System.out.println(india.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
// 2023-11-15T03:43:20+05:30[Asia/Kolkata]

// 4. Human date → epoch
ZonedDateTime dt = ZonedDateTime.parse("2024-01-15T10:30:00Z");
long epoch = dt.toEpochSecond();   // 1705314600

Epoch milliseconds

Instant.now().toEpochMilli()

Epoch seconds

Instant.now().getEpochSecond()

From epoch ms

Instant.ofEpochMilli(ms)

Key properties of Java epoch time: it uses millisecond precision by default (unlike Unix seconds), is timezone-independent (always UTC-based), and the Instant class is immutable and thread-safe. Always convert to local time only at the display layer.