🕐
← Torna alle guide

Lavorare con i timestamp Unix nei linguaggi di programmazione

· Tag: javascript, python, php, golang, programming, unix-timestamp, epoch, database

Perché i timestamp Unix nella programmazione?

I timestamp Unix sono la valuta universale del tempo nel software. Rendono banale l'aritmetica delle date (basta aggiungere o sottrarre secondi), eliminano la confusione dei fusi orari e si serializzano in modo pulito in JSON. Ogni linguaggio di programmazione fornisce funzioni semplici per lavorare con essi, ma le API differiscono in modo sottile. Questa guida copre i linguaggi più comuni e le loro migliori pratiche.

JavaScript (Browser e Node.js)

JavaScript utilizza i millisecondi per il suo oggetto Date, mentre la maggior parte degli altri sistemi usa i secondi. Questa è la fonte più comune di bug.

Ottenere il timestamp corrente

// 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();

Convertire un timestamp in una data

// 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

Analizzare una stringa di data in un 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);

Attenzione: il comportamento di Date.parse() varia tra i browser per stringhe di data non standard. L'uso del formato ISO 8601 con uno specificatore di fuso orario (Z per UTC) è la scelta più sicura.

Lavorare con i fusi orari 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

Per operazioni avanzate sui fusi orari, si consiglia l'API Intl.DateTimeFormat o librerie come date-fns-tz e Luxon.

Python

Python fornisce sia moduli di basso livello (time) che di alto livello (datetime) per lavorare con i timestamp.

Ottenere il timestamp corrente

import time

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

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

Convertire un timestamp in un 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

Analizzare una stringa di data in un 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()

Lavorare con Pandas (analisi dei dati)

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 ha l'API più semplice per le operazioni sui timestamp.

Ottenere il timestamp corrente

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

Convertire un timestamp in una data

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

Il pacchetto time di Go è ben progettato ma richiede una comprensione esplicita dei tipi coinvolti.

Ottenere il timestamp corrente

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

Convertire un timestamp in una data

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"));

Archiviazione nei database: migliori pratiche

Scegliere il tipo di colonna giusto

| Database | Tipo consigliato | Note | |----------|-----------------|-------| | PostgreSQL | TIMESTAMP WITH TIME ZONE o BIGINT | Il tipo timestamp nativo è preferito | | MySQL / MariaDB | INT UNSIGNED (per date fino al 2106) o BIGINT | Evita il tipo TIMESTAMP (l'intervallo termina nel 2038) | | SQLite | INTEGER | SQLite non ha un tipo timestamp nativo | | MongoDB | Oggetto Date o int64 | BSON Date è internamente un timestamp a 64 bit |

Esempio PostgreSQL

-- 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;

Esempio MySQL

-- 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;

Tabella comparativa dei linguaggi

| Linguaggio | Timestamp corrente | Timestamp in data | Data in timestamp | Risoluzione | |----------|-------------------|-------------------|-------------------|------------| | JavaScript | Date.now() | new Date(ts * 1000) | Date.parse(str) / 1000 | Millisecondi | | Python | time.time() | datetime.fromtimestamp(ts) | datetime.strptime(str).timestamp() | Secondi float | | PHP | time() | date("Y-m-d", ts) | strtotime(str) | Secondi | | Go | time.Now().Unix() | time.Unix(ts, 0) | time.Parse(layout, str).Unix() | Secondi | | Rust | SystemTime::now() | NaiveDateTime::from_timestamp_opt() | — | Varie |

Qualunque linguaggio tu usi, il nostro Convertitore di timestamp Unix è un compagno affidabile per controlli rapidi e debug.