High-precision timestamps are essential in modern computing for logging, performance measurement, distributed systems, and financial applications. This guide covers everything you need to know about working with nanosecond, microsecond, and millisecond timestamps.
📋 Table of Contents
- Key Takeaways
- Understanding Timestamp Precision
- Identifying Timestamp Precision
- Converting High-Precision Timestamps
- Multi-Language Implementation
- Common Use Cases
- Precision Considerations
- FAQ
- Conclusion
Key Takeaways
- Precision Levels: Seconds (10 digits), milliseconds (13 digits), microseconds (16 digits), nanoseconds (19 digits).
- Auto-Detection: Most tools can detect precision by digit count.
- Conversion Formula: Divide by 1000 for each precision level down (ns → μs → ms → s).
- Language Support: JavaScript supports milliseconds natively; other languages vary.
- Use Cases: Nanoseconds for performance profiling, microseconds for logging, milliseconds for general use.
Need to convert high-precision timestamps? Try our free online tool:
Understanding Timestamp Precision
Unix timestamps represent time as the number of time units since January 1, 1970 (UTC). Different precision levels serve different purposes:
| Precision | Unit | Digits | Example | Use Case |
|---|---|---|---|---|
| Seconds | s | 10 | 1706198400 |
General purpose |
| Milliseconds | ms | 13 | 1706198400000 |
Web applications |
| Microseconds | μs | 16 | 1706198400000000 |
Database logging |
| Nanoseconds | ns | 19 | 1706198400000000000 |
Performance profiling |
Precision Comparison
Seconds: 1706198400
Milliseconds: 1706198400000
Microseconds: 1706198400000000
Nanoseconds: 1706198400000000000
All represent: January 25, 2024 12:00:00 UTC
Real-World Precision
| Precision | Resolution | Events per Second |
|---|---|---|
| Seconds | 1s | 1 |
| Milliseconds | 0.001s | 1,000 |
| Microseconds | 0.000001s | 1,000,000 |
| Nanoseconds | 0.000000001s | 1,000,000,000 |
Identifying Timestamp Precision
The easiest way to identify timestamp precision is by counting digits:
function detectTimestampPrecision(timestamp) {
const str = String(timestamp);
const digits = str.length;
if (digits <= 10) return 'seconds';
if (digits <= 13) return 'milliseconds';
if (digits <= 16) return 'microseconds';
return 'nanoseconds';
}
// Examples
detectTimestampPrecision(1706198400); // 'seconds'
detectTimestampPrecision(1706198400000); // 'milliseconds'
detectTimestampPrecision(1706198400000000); // 'microseconds'
detectTimestampPrecision(1706198400000000000); // 'nanoseconds'
Quick Reference Table
| Digits | Precision | Conversion to Seconds |
|---|---|---|
| 10 | Seconds | ÷ 1 |
| 13 | Milliseconds | ÷ 1,000 |
| 16 | Microseconds | ÷ 1,000,000 |
| 19 | Nanoseconds | ÷ 1,000,000,000 |
Converting High-Precision Timestamps
Using Our Online Tool
The easiest way to convert any timestamp:
- Visit Timestamp Converter
- Paste your timestamp (any precision)
- The tool auto-detects precision and converts
- View results in multiple formats
Manual Conversion
// Nanoseconds to Date
function nanosToDate(nanos) {
// Convert to milliseconds (JavaScript Date uses ms)
const ms = Math.floor(nanos / 1000000);
return new Date(ms);
}
// Microseconds to Date
function microsToDate(micros) {
const ms = Math.floor(micros / 1000);
return new Date(ms);
}
// Examples
const nsTimestamp = 1706198400000000000n; // Use BigInt for precision
const date = nanosToDate(Number(nsTimestamp));
console.log(date.toISOString());
// Output: 2024-01-25T12:00:00.000Z
Conversion Formulas
Nanoseconds → Microseconds: ns ÷ 1,000
Microseconds → Milliseconds: μs ÷ 1,000
Milliseconds → Seconds: ms ÷ 1,000
Nanoseconds → Seconds: ns ÷ 1,000,000,000
Nanoseconds → Milliseconds: ns ÷ 1,000,000
Multi-Language Implementation
JavaScript/Node.js
// JavaScript has limited precision for large numbers
// Use BigInt for nanosecond timestamps
function convertTimestamp(timestamp) {
const str = String(timestamp);
const digits = str.length;
let ms;
if (digits <= 10) {
ms = Number(timestamp) * 1000;
} else if (digits <= 13) {
ms = Number(timestamp);
} else if (digits <= 16) {
ms = Math.floor(Number(timestamp) / 1000);
} else {
// Nanoseconds - use BigInt
ms = Number(BigInt(timestamp) / 1000000n);
}
return new Date(ms);
}
// Get current timestamp in different precisions
const now = Date.now(); // Milliseconds
const nowMicros = now * 1000; // Microseconds (approximate)
const nowNanos = BigInt(now) * 1000000n; // Nanoseconds (approximate)
console.log('Milliseconds:', now);
console.log('Microseconds:', nowMicros);
console.log('Nanoseconds:', nowNanos.toString());
Python
import time
from datetime import datetime
def convert_timestamp(timestamp):
"""Convert any precision timestamp to datetime."""
ts_str = str(timestamp)
digits = len(ts_str)
if digits <= 10:
return datetime.fromtimestamp(timestamp)
elif digits <= 13:
return datetime.fromtimestamp(timestamp / 1000)
elif digits <= 16:
return datetime.fromtimestamp(timestamp / 1000000)
else:
return datetime.fromtimestamp(timestamp / 1000000000)
# Get current timestamp in different precisions
now_s = int(time.time()) # Seconds
now_ms = int(time.time() * 1000) # Milliseconds
now_us = int(time.time() * 1000000) # Microseconds
now_ns = int(time.time() * 1000000000) # Nanoseconds
# Python 3.7+ has time.time_ns() for true nanosecond precision
now_ns_precise = time.time_ns()
print(f"Seconds: {now_s}")
print(f"Milliseconds: {now_ms}")
print(f"Microseconds: {now_us}")
print(f"Nanoseconds: {now_ns_precise}")
# Convert nanosecond timestamp
ns_timestamp = 1706198400000000000
dt = convert_timestamp(ns_timestamp)
print(f"Converted: {dt}")
Go
package main
import (
"fmt"
"time"
)
func convertTimestamp(timestamp int64) time.Time {
digits := len(fmt.Sprintf("%d", timestamp))
switch {
case digits <= 10:
return time.Unix(timestamp, 0)
case digits <= 13:
return time.UnixMilli(timestamp)
case digits <= 16:
return time.UnixMicro(timestamp)
default:
return time.Unix(0, timestamp) // Nanoseconds
}
}
func main() {
// Get current time in different precisions
now := time.Now()
fmt.Println("Seconds:", now.Unix())
fmt.Println("Milliseconds:", now.UnixMilli())
fmt.Println("Microseconds:", now.UnixMicro())
fmt.Println("Nanoseconds:", now.UnixNano())
// Convert nanosecond timestamp
nsTimestamp := int64(1706198400000000000)
converted := convertTimestamp(nsTimestamp)
fmt.Println("Converted:", converted.Format(time.RFC3339Nano))
}
Java
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
public class TimestampConverter {
public static Instant convertTimestamp(long timestamp) {
int digits = String.valueOf(timestamp).length();
if (digits <= 10) {
return Instant.ofEpochSecond(timestamp);
} else if (digits <= 13) {
return Instant.ofEpochMilli(timestamp);
} else if (digits <= 16) {
long seconds = timestamp / 1000000;
long nanoAdjustment = (timestamp % 1000000) * 1000;
return Instant.ofEpochSecond(seconds, nanoAdjustment);
} else {
long seconds = timestamp / 1000000000;
long nanoAdjustment = timestamp % 1000000000;
return Instant.ofEpochSecond(seconds, nanoAdjustment);
}
}
public static void main(String[] args) {
// Get current time in different precisions
Instant now = Instant.now();
System.out.println("Seconds: " + now.getEpochSecond());
System.out.println("Milliseconds: " + now.toEpochMilli());
System.out.println("Nanoseconds: " +
(now.getEpochSecond() * 1000000000L + now.getNano()));
// Convert nanosecond timestamp
long nsTimestamp = 1706198400000000000L;
Instant converted = convertTimestamp(nsTimestamp);
System.out.println("Converted: " + converted);
}
}
Common Use Cases
1. Performance Profiling
// Measure execution time with high precision
const start = process.hrtime.bigint(); // Nanoseconds
// ... code to measure ...
const end = process.hrtime.bigint();
const durationNs = end - start;
const durationMs = Number(durationNs) / 1000000;
console.log(`Execution time: ${durationNs}ns (${durationMs}ms)`);
2. Database Logging
-- PostgreSQL supports microsecond precision
CREATE TABLE events (
id SERIAL PRIMARY KEY,
event_name VARCHAR(255),
created_at TIMESTAMP(6) DEFAULT NOW() -- 6 = microseconds
);
-- Store nanosecond timestamp as BIGINT
CREATE TABLE high_precision_events (
id SERIAL PRIMARY KEY,
event_name VARCHAR(255),
timestamp_ns BIGINT
);
3. Distributed Systems
# Generate unique IDs with nanosecond timestamps
import time
import uuid
def generate_time_based_id():
"""Generate ID with nanosecond timestamp prefix."""
ns = time.time_ns()
unique = uuid.uuid4().hex[:8]
return f"{ns}-{unique}"
# Example: 1706198400000000000-a1b2c3d4
4. Financial Applications
// High-frequency trading requires nanosecond precision
public class Trade {
private long timestampNanos;
private String symbol;
private double price;
public Trade(String symbol, double price) {
this.timestampNanos = System.nanoTime();
this.symbol = symbol;
this.price = price;
}
}
Precision Considerations
JavaScript Limitations
// JavaScript Number has 53-bit precision
// Nanosecond timestamps exceed this!
const nsTimestamp = 1706198400000000000;
console.log(nsTimestamp);
// Output: 1706198400000000000 (may lose precision!)
// Use BigInt for nanoseconds
const nsTimestampBigInt = 1706198400000000000n;
console.log(nsTimestampBigInt.toString());
// Output: 1706198400000000000 (exact)
Database Storage
| Database | Max Precision | Storage Type |
|---|---|---|
| PostgreSQL | Microseconds | TIMESTAMP(6) |
| MySQL | Microseconds | DATETIME(6) |
| MongoDB | Milliseconds | Date |
| ClickHouse | Nanoseconds | DateTime64(9) |
API Transmission
// JSON doesn't support BigInt natively
// Use string for nanosecond timestamps
{
"event": "user_login",
"timestamp_ns": "1706198400000000000",
"timestamp_ms": 1706198400000
}
FAQ
What's the difference between Unix timestamp precisions?
| Precision | Definition | Example |
|---|---|---|
| Seconds | Seconds since epoch | 1706198400 |
| Milliseconds | 1/1000 second | 1706198400000 |
| Microseconds | 1/1000000 second | 1706198400000000 |
| Nanoseconds | 1/1000000000 second | 1706198400000000000 |
When should I use nanosecond timestamps?
Use nanoseconds for:
- Performance benchmarking
- High-frequency trading
- Distributed system event ordering
- Scientific measurements
Use milliseconds for:
- Web applications
- User-facing timestamps
- General logging
How do I handle nanosecond timestamps in JavaScript?
// Use BigInt for storage and calculation
const ns = BigInt("1706198400000000000");
// Convert to Date (loses nanosecond precision)
const date = new Date(Number(ns / 1000000n));
// For display, keep as string
const nsString = ns.toString();
Can databases store nanosecond timestamps?
Most databases support microseconds. For nanoseconds:
- Store as BIGINT
- Use specialized time-series databases (InfluxDB, TimescaleDB)
- ClickHouse supports DateTime64(9) for nanoseconds
How accurate are system clocks at nanosecond level?
System clocks vary:
- Standard OS: ~1ms accuracy
- NTP synchronized: ~1-10ms accuracy
- PTP (Precision Time Protocol): ~1μs accuracy
- GPS/atomic clock: ~1ns accuracy
For most applications, the timestamp precision exceeds clock accuracy.
Conclusion
Understanding timestamp precision is crucial for modern applications. Whether you're building performance monitoring tools, distributed systems, or financial applications, choosing the right precision level ensures accurate time tracking without unnecessary overhead.
Quick Reference:
- ✅ Use seconds/milliseconds for general applications
- ✅ Use microseconds for database logging
- ✅ Use nanoseconds for performance profiling
- ✅ Use BigInt in JavaScript for nanoseconds
- ✅ Store nanoseconds as strings in JSON
Need to convert timestamps? Use our free online tool: