Travailler avec les horodatages Unix dans les langages de programmation
Pourquoi les horodatages Unix en programmation ?
Les horodatages Unix sont la monnaie universelle du temps en informatique. Ils rendent l'arithmétique des dates triviale (il suffit d'ajouter ou de soustraire des secondes), éliminent la confusion des fuseaux horaires et se sérialisent proprement en JSON. Chaque langage de programmation fournit des fonctions simples pour les utiliser, mais les API diffèrent subtilement. Ce guide couvre les langages les plus courants et leurs meilleures pratiques.
JavaScript (Navigateur et Node.js)
JavaScript utilise les millisecondes pour son objet Date, tandis que la plupart des autres systèmes utilisent des secondes. C'est la source de bugs la plus courante.
Obtenir l'horodatage actuel
// 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 un horodatage en date
// 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
Analyser une chaîne de date en horodatage
// 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);
Avertissement : le comportement de Date.parse() varie selon les navigateurs pour les chaînes de date non standard. L'utilisation du format ISO 8601 avec un indicateur de fuseau horaire (Z pour UTC) est la plus sûre.
Travailler avec les fuseaux horaires 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
Pour les opérations avancées sur les fuseaux horaires, l'API Intl.DateTimeFormat ou des bibliothèques comme date-fns-tz et Luxon sont recommandées.
Python
Python fournit à la fois des modules de bas niveau (time) et de haut niveau (datetime) pour travailler avec les horodatages.
Obtenir l'horodatage actuel
import time
# Seconds as a float (including fractional milliseconds)
current = time.time()
# Example: 1785292800.123456
# As an integer
current_int = int(time.time())
Convertir un horodatage en 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
Analyser une chaîne de date en horodatage
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()
Travailler avec Pandas (Analyse de données)
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 possède l'API la plus simple pour les opérations sur les horodatages.
Obtenir l'horodatage actuel
<?php
$now = time(); // Integer: 1785292800
$nowMicro = microtime(); // String: "0.12345600 1785292800"
$nowFloat = microtime(true); // Float: 1785292800.1235
Convertir un horodatage en date
<?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
Le package time de Go est bien conçu mais exige une compréhension explicite des types impliqués.
Obtenir l'horodatage actuel
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 un horodatage en date
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"));
Stockage en base de données : meilleures pratiques
Choisir le bon type de colonne
| Base de données | Type recommandé | Notes |
|----------|-----------------|-------|
| PostgreSQL | TIMESTAMP WITH TIME ZONE ou BIGINT | Le type d'horodatage natif est préféré |
| MySQL / MariaDB | INT UNSIGNED (pour les dates jusqu'en 2106) ou BIGINT | Évitez le type TIMESTAMP (la plage se termine en 2038) |
| SQLite | INTEGER | SQLite n'a pas de type d'horodatage natif |
| MongoDB | Objet Date ou int64 | La date BSON est en interne un horodatage 64 bits |
Exemple 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;
Exemple 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;
Tableau comparatif des langages
| Langage | Horodatage actuel | Horodatage vers date | Date vers horodatage | Résolution |
|----------|-------------------|-------------------|-------------------|------------|
| JavaScript | Date.now() | new Date(ts * 1000) | Date.parse(str) / 1000 | Millisecondes |
| Python | time.time() | datetime.fromtimestamp(ts) | datetime.strptime(str).timestamp() | Secondes flottantes |
| PHP | time() | date("Y-m-d", ts) | strtotime(str) | Secondes |
| Go | time.Now().Unix() | time.Unix(ts, 0) | time.Parse(layout, str).Unix() | Secondes |
| Rust | SystemTime::now() | NaiveDateTime::from_timestamp_opt() | — | Diverses |
Quel que soit le langage que vous utilisez, notre Convertisseur d'horodatage Unix est un compagnon fiable pour les vérifications rapides et le débogage.