🕐
← Volver a guías

Trabajar con marcas de tiempo Unix en lenguajes de programación

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

¿Por qué usar marcas de tiempo Unix en programación?

Las marcas de tiempo Unix son la moneda universal del tiempo en el software. Hacen que la aritmética de fechas sea trivial (solo hay que sumar o restar segundos), eliminan la confusión de las zonas horarias y se serializan limpiamente a JSON. Todos los lenguajes de programación proporcionan funciones sencillas para trabajar con ellas, pero las APIs difieren sutilmente. Esta guía cubre los lenguajes más comunes y sus mejores prácticas.

JavaScript (Navegador y Node.js)

JavaScript usa milisegundos para su objeto Date, mientras que la mayoría de los demás sistemas usan segundos. Esta es la fuente más común de errores.

Obtener la marca de tiempo actual

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

Convertir una marca de tiempo a una fecha

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

Analizar una cadena de fecha a una marca de tiempo

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

Advertencia: El comportamiento de Date.parse() varía entre navegadores para cadenas de fecha no estándar. Usar el formato ISO 8601 con un especificador de zona horaria (Z para UTC) es lo más seguro.

Trabajar con zonas horarias en 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

Para operaciones avanzadas de zona horaria, se recomiendan la API Intl.DateTimeFormat o bibliotecas como date-fns-tz y Luxon.

Python

Python proporciona módulos tanto de bajo nivel (time) como de alto nivel (datetime) para trabajar con marcas de tiempo.

Obtener la marca de tiempo actual

import time

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

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

Convertir una marca de tiempo a 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

Analizar una cadena de fecha a una marca de tiempo

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

Trabajar con Pandas (análisis de datos)

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 tiene la API más simple para operaciones con marcas de tiempo.

Obtener la marca de tiempo actual

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

Convertir una marca de tiempo a una fecha

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

El paquete time de Go está bien diseñado, pero requiere una comprensión explícita de los tipos involucrados.

Obtener la marca de tiempo actual

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

Convertir una marca de tiempo a una fecha

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

Almacenamiento en bases de datos: mejores prácticas

Elegir el tipo de columna correcto

| Base de datos | Tipo recomendado | Notas | |----------|-----------------|-------| | PostgreSQL | TIMESTAMP WITH TIME ZONE o BIGINT | Se prefiere el tipo de marca de tiempo nativo | | MySQL / MariaDB | INT UNSIGNED (para fechas hasta 2106) o BIGINT | Evita el tipo TIMESTAMP (el rango termina en 2038) | | SQLite | INTEGER | SQLite no tiene un tipo de marca de tiempo nativo | | MongoDB | Objeto Date o int64 | La fecha BSON es internamente una marca de tiempo de 64 bits |

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

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

Tabla comparativa de lenguajes

| Lenguaje | Marca de tiempo actual | Marca de tiempo a fecha | Fecha a marca de tiempo | Resolución | |----------|-------------------|-------------------|-------------------|------------| | JavaScript | Date.now() | new Date(ts * 1000) | Date.parse(str) / 1000 | Milisegundos | | Python | time.time() | datetime.fromtimestamp(ts) | datetime.strptime(str).timestamp() | Segundos flotantes | | PHP | time() | date("Y-m-d", ts) | strtotime(str) | Segundos | | Go | time.Now().Unix() | time.Unix(ts, 0) | time.Parse(layout, str).Unix() | Segundos | | Rust | SystemTime::now() | NaiveDateTime::from_timestamp_opt() | — | Varias |

Cualquiera que sea el lenguaje que uses, nuestro Convertidor de marcas de tiempo Unix es un compañero fiable para comprobaciones rápidas y depuración.