Quando converter data para Epoch no código
A maioria das apps armazena timestamps como inteiros Unix, mas recebe datas como strings — um valor de calendário num formulário, uma coluna de data num CSV, um campo de webhook formatado num fuso específico. Converter essas strings em epoch no código é o que permite a bancos ordená-las, a serviços compará-las e a APIs aceitá-las. Este guia mostra a forma idiomática em JavaScript, Python, SQL, Go e shell, mais os bugs de fuso horário que toda equipe acaba encontrando.
JavaScript: Date, getTime e entrada com fuso horário
JavaScript guarda o tempo em milissegundos. Date.UTC retorna o epoch em ms para uma hora-parede UTC. Para uma string ISO 8601 com offset explícito use new Date(iso).getTime(). Divida por 1000 para obter segundos.
- 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
O objeto datetime do Python converte para epoch via .timestamp(), mas só quando é timezone-aware. Um datetime naive é interpretado como hora local do host, que é a causa mais comum de valores epoch errados em produção.
- 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
Todo banco de dados grande expõe uma função para materializar um inteiro epoch a partir de uma coluna timestamp. Trate o fuso da coluna explicitamente: TIMESTAMP WITH TIME ZONE e TIMESTAMP WITHOUT TIME ZONE se comportam de forma muito diferente nessas funções.
- 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
Em Go, faça parse com um layout que inclua o offset, depois chame .Unix() para segundos ou .UnixMilli() para milissegundos. Em shell, GNU date -d entende strings de data comuns; BSD/macOS date -j -f exige formato explícito.
- 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.