← Tutti gli articoli

Convertire data in Epoch in JavaScript, Python, SQL e Go

Tutorial per sviluppatori: convertire una data e fuso orario in Unix epoch in JavaScript, Python, SQL, Go e shell. Tratta il parsing timezone-aware vs naive, il gap DST e la scelta tra secondi e millisecondi.

Quando serve convertire data in Epoch nel codice

La maggior parte delle app memorizza i timestamp come interi Unix, ma riceve date come stringhe — un valore di calendario in un form, una colonna data in un CSV, un campo webhook formattato in un fuso specifico. Convertire queste stringhe in epoch nel codice è ciò che permette ai database di ordinarle, ai servizi di confrontarle e alle API di accettarle. Questa guida mostra il modo idiomatico in JavaScript, Python, SQL, Go e shell, e i bug di fuso orario che ogni team prima o poi incontra.

JavaScript: Date, getTime e input con fuso orario

JavaScript memorizza il tempo in millisecondi. Date.UTC restituisce l'epoch in ms per un'ora-muro UTC. Per una stringa ISO 8601 con offset esplicito usa new Date(iso).getTime(). Dividi per 1000 per ottenere secondi.

  • Date.UTC(2026, 0, 1, 0, 0, 0) → 1767225600000 (month is zero-indexed)
  • new Date('2026-01-01T08:00:00-05:00').getTime() → 1767265200000
  • Math.floor(Date.now() / 1000) → current Unix seconds
  • Wall-clock in a non-UTC zone needs a zone-aware library (Luxon, date-fns-tz, Temporal)

Python: datetime.timestamp e calendar.timegm

L'oggetto datetime di Python si converte in epoch tramite .timestamp(), ma solo se è timezone-aware. Un datetime naive viene interpretato come ora locale dell'host, che è la causa più comune di valori epoch errati in produzione.

  • datetime(2026, 1, 1, tzinfo=timezone.utc).timestamp() → 1767225600.0
  • calendar.timegm(struct_time) → seconds (UTC-only)
  • datetime.now(ZoneInfo('America/New_York')).timestamp() → zone-aware now
  • Avoid datetime.fromisoformat(s).timestamp() when s has no offset

SQL: EXTRACT EPOCH, UNIX_TIMESTAMP, UNIX_SECONDS

Ogni database principale espone una funzione per ottenere un intero epoch da una colonna timestamp. Tratta esplicitamente il fuso della colonna: TIMESTAMP WITH TIME ZONE e TIMESTAMP WITHOUT TIME ZONE si comportano in modo molto diverso passandoli a queste funzioni.

  • PostgreSQL: EXTRACT(EPOCH FROM ts) → seconds (double)
  • MySQL: UNIX_TIMESTAMP(ts) → seconds, naive ts read in session timezone
  • BigQuery: UNIX_SECONDS(ts) / UNIX_MILLIS(ts) — TIMESTAMP only
  • SQLite: strftime('%s', ts) → seconds as string, cast to integer

Go e shell: time.Unix e date +%s

In Go fai parse con un layout che include l'offset, poi chiama .Unix() per i secondi o .UnixMilli() per i millisecondi. In shell GNU date -d capisce stringhe di data comuni, BSD/macOS date -j -f richiede un formato esplicito.

  • Go: t, _ := time.Parse(time.RFC3339, "2026-01-01T00:00:00Z"); t.Unix()
  • Go: time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC).Unix()
  • GNU date: date -d "2026-01-01 00:00:00 UTC" +%s
  • macOS date: date -j -u -f "%Y-%m-%d %H:%M:%S" "2026-01-01 00:00:00" +%s

FAQ

How do I convert time to epoch time?
Choose the date, clock time, and timezone, then convert that instant to Unix seconds or milliseconds. If the timezone is missing, the result may be off by hours.
Is timestamp to epoch the same as date to epoch?
Usually yes. It means converting a readable timestamp or date-time string into an epoch number.
Should I send epoch seconds or milliseconds to an API?
Follow the API documentation. If it says Unix timestamp, it often means seconds, but JavaScript-oriented APIs may expect milliseconds.
Why does the same date give a different epoch in different timezones?
Because a local wall-clock time only identifies an instant once a timezone is attached. 2026-01-01 00:00 is 1767225600 in UTC but 1767243600 in New York — five hours later in real time. Set the timezone before converting.