โ† Back to Guides

Working with Unix Timestamps in Programming Languages

ยท Tags: javascript, python, php, golang, programming, unix-timestamp, epoch, database

Why Unix Timestamps in Programming?

Unix timestamps are the universal currency of time in software. They make date arithmetic trivial (just add or subtract seconds), eliminate timezone confusion, and serialize cleanly to JSON. Every programming language provides straightforward functions for working with them, but the APIs differ subtly. This guide covers the most common languages and their best practices.

JavaScript (Browser and Node.js)

JavaScript uses milliseconds for its Date object, while most other systems use seconds. This is the most common source of bugs.

Getting the Current Timestamp

// Milliseconds since epoch (standard JavaScript)
const nowMs = Date.now();         // 1785292800000

// Seconds since epoch (for compatibility)
const nowSec = Math.floor(Date.now() / 1000);  // 1785292800

// Node.js high-resolution timer (microseconds)
const hrTime = process.hrtime.bigint();

Converting a Timestamp to a Date

// From seconds (most APIs and databases)
const timestamp = 1785292800;
const date = new Date(timestamp * 1000);  // Multiply by 1000!

// From milliseconds (JavaScript native)
const dateFromMs = new Date(1785292800000);

// Format the result
console.log(date.toISOString());
// Output: 2026-07-19T00:00:00.000Z

console.log(date.toLocaleString("en-US", { timeZone: "America/New_York" }));
// Output: 7/18/2026, 8:00:00 PM

Parsing a Date String to a Timestamp

// Using Date.parse() (returns milliseconds)
const ms = Date.parse("2026-07-19T00:00:00Z");
const sec = ms / 1000;  // 1785292800

// Using Date constructor
const ts = Math.floor(new Date("2026-07-19 UTC").getTime() / 1000);

Warning: Date.parse() behavior varies across browsers for non-standard date strings. Using ISO 8601 format with a timezone specifier (Z for UTC) is safest.

Working with Timezones in JavaScript

// Format in a specific timezone
const date = new Date(1785292800 * 1000);
const options = {
  timeZone: "Asia/Tokyo",
  year: "numeric", month: "2-digit", day: "2-digit",
  hour: "2-digit", minute: "2-digit", second: "2-digit",
};
console.log(date.toLocaleString("ja-JP", options));
// Output: 07/19/2026 09:00:00

For advanced timezone operations, the Intl.DateTimeFormat API or libraries like date-fns-tz and Luxon are recommended.

Python

Python provides both low-level (time) and high-level (datetime) modules for working with timestamps.

Getting the Current Timestamp

import time

# Seconds as a float (including fractional milliseconds)
current = time.time()
# Example: 1785292800.123456

# As an integer
current_int = int(time.time())

Converting a Timestamp to a Datetime

from datetime import datetime

# UTC datetime (Python 3.x)
dt_utc = datetime.utcfromtimestamp(1785292800)

# Timezone-aware datetime (Python 3.9+ with zoneinfo)
from zoneinfo import ZoneInfo
dt_tokyo = datetime.fromtimestamp(1785292800, tz=ZoneInfo("Asia/Tokyo"))

# Formatted string
print(dt_utc.strftime("%Y-%m-%d %H:%M:%S"))
# Output: 2026-07-19 00:00:00

Parsing a Date String to a Timestamp

import time
from datetime import datetime

# From date string
dt = datetime.strptime("2026-07-19 00:00:00", "%Y-%m-%d %H:%M:%S")
timestamp = time.mktime(dt.timetuple())  # Treats as local time

# For UTC input
from datetime import timezone
timestamp_utc = dt.replace(tzinfo=timezone.utc).timestamp()

Working with Pandas (Data Analysis)

import pandas as pd

# Convert a column of Unix timestamps to datetime
df["timestamp"] = pd.to_datetime(df["unix_seconds"], unit="s")

# Convert to different units
df["datetime_ms"] = pd.to_datetime(df["unix_milliseconds"], unit="ms")

# Set a timezone
df["timestamp_ny"] = df["timestamp"].dt.tz_localize("UTC").dt.tz_convert("America/New_York")

PHP

PHP has the simplest API for timestamp operations.

Getting the Current Timestamp

<?php
$now = time();           // Integer: 1785292800
$nowMicro = microtime();  // String: "0.12345600 1785292800"
$nowFloat = microtime(true);  // Float: 1785292800.1235

Converting a Timestamp to a Date

<?php
echo date("Y-m-d H:i:s", 1785292800);
// Output: 2026-07-19 00:00:00

// With timezone
$tz = new DateTimeZone("Europe/London");
$dt = new DateTime("@1785292800");
$dt->setTimezone($tz);
echo $dt->format("Y-m-d H:i:s");

Go

Go's time package is well-designed but requires explicit understanding of the types involved.

Getting the Current Timestamp

package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()
    sec := now.Unix()            // int64 seconds
    milli := now.UnixMilli()     // int64 milliseconds
    nano := now.UnixNano()       // int64 nanoseconds
    fmt.Printf("Seconds: %d\n", sec)
}

Converting a Timestamp to a Date

t := time.Unix(1785292800, 0)
fmt.Println(t.UTC())
// Output: 2026-07-19 00:00:00 +0000 UTC

// Format as string
fmt.Println(t.Format("2006-01-02 15:04:05"))
// Output: 2026-07-19 00:00:00

// With timezone
loc, _ := time.LoadLocation("America/Chicago")
fmt.Println(t.In(loc))

Rust

use std::time::{SystemTime, UNIX_EPOCH};

// Current timestamp
let now = SystemTime::now()
    .duration_since(UNIX_EPOCH)
    .expect("Time went backwards");
println!("Seconds: {}", now.as_secs());

// Timestamp to date
let dt = chrono::NaiveDateTime::from_timestamp_opt(1785292800, 0).unwrap();
println!("{}", dt.format("%Y-%m-%d %H:%M:%S"));

Database Storage: Best Practices

Choosing the Right Column Type

| Database | Recommended Type | Notes | |----------|-----------------|-------| | PostgreSQL | TIMESTAMP WITH TIME ZONE or BIGINT | Native timestamp type is preferred | | MySQL / MariaDB | INT UNSIGNED (for dates up to 2106) or BIGINT | Avoid TIMESTAMP type (range ends at 2038) | | SQLite | INTEGER | SQLite has no native timestamp type | | MongoDB | Date object or int64 | BSON Date is internally a 64-bit timestamp |

PostgreSQL Example

-- Store as native timestamp
CREATE TABLE events (
    id SERIAL PRIMARY KEY,
    occurred_at TIMESTAMP WITH TIME ZONE NOT NULL,
    payload JSONB
);

-- Insert with current time
INSERT INTO events (occurred_at) VALUES (NOW());

-- Query as Unix timestamp
SELECT EXTRACT(EPOCH FROM occurred_at) AS unix_ts FROM events;

MySQL Example

-- Using BIGINT for future-proof storage
CREATE TABLE logs (
    id INT AUTO_INCREMENT PRIMARY KEY,
    event_time BIGINT NOT NULL,
    message TEXT
);

-- Insert current timestamp
INSERT INTO logs (event_time, message) VALUES (UNIX_TIMESTAMP(), 'Server started');

-- Query and convert
SELECT FROM_UNIXTIME(event_time) AS readable_time FROM logs;

Language Comparison Table

| Language | Current Timestamp | Timestamp to Date | Date to Timestamp | Resolution | |----------|-------------------|-------------------|-------------------|------------| | JavaScript | Date.now() | new Date(ts * 1000) | Date.parse(str) / 1000 | Milliseconds | | Python | time.time() | datetime.fromtimestamp(ts) | datetime.strptime(str).timestamp() | Float seconds | | PHP | time() | date("Y-m-d", ts) | strtotime(str) | Seconds | | Go | time.Now().Unix() | time.Unix(ts, 0) | time.Parse(layout, str).Unix() | Seconds | | Rust | SystemTime::now() | NaiveDateTime::from_timestamp_opt() | โ€” | Various |

Whichever language you use, our Unix Timestamp Converter is a reliable companion for quick checks and debugging.