Guides

Comprendre les formats de timestamp

Introduction

Les timestamps existent sous différents formats et niveaux de précision. Les comprendre est essentiel pour travailler avec des données temporelles, des APIs, des bases de données et des systèmes distribués.

Résumé rapide : les timestamps Unix (secondes, millisecondes, microsecondes, nanosecondes), les chaînes ISO 8601 et le format RFC 3339 sont les plus courants. Chacun a un usage spécifique en développement logiciel.

Formats de timestamp Unix

Epoch Unix (temps POSIX)

Un timestamp Unix représente le temps comme un nombre de secondes/millisecondes depuis le 1er janvier 1970, 00:00:00 UTC.

Unix Epoch Reference:
  Start Date: January 1, 1970, 00:00:00 UTC
  Current: January 1, 2026, 00:00:00 UTC
  Timestamp: 1735689600 (seconds)

Niveaux de précision

PrécisionExempleMagnitudeUsage courant
Secondes173568960010 chiffresSystèmes Unix/Linux
Millisecondes1735689600000013 chiffresJavaScript, APIs web
Microsecondes17356896000000000016 chiffresMesure haute précision
Nanosecondes17356896000000000000019 chiffresCalcul scientifique

Exemples de code : différentes précisions

// JavaScript uses milliseconds by default
const msTimestamp = Date.now(); // 17356896000000
const secTimestamp = Math.floor(Date.now() / 1000); // 1735689600
const nsTimestamp = Date.now() * 1000000; // 173568960000000000000

console.log('Milliseconds:', msTimestamp);
console.log('Seconds:', secTimestamp);
console.log('Nanoseconds:', nsTimestamp);
from datetime import datetime
import time

# Python supports multiple precisions
now = datetime.now(datetime.timezone.utc)
sec_timestamp = int(now.timestamp())
ms_timestamp = int(now.timestamp() * 1000)
us_timestamp = int(now.timestamp() * 1000000)
ns_timestamp = int(now.timestamp() * 1000000000)

print(f'Seconds: {sec_timestamp}')
print(f'Milliseconds: {ms_timestamp}')
print(f'Microseconds: {us_timestamp}')
print(f'Nanoseconds: {ns_timestamp}')
import java.time.Instant;

// Java supports multiple precisions
Instant now = Instant.now();
long secTimestamp = now.getEpochSecond(); // 1735689600
long msTimestamp = now.toEpochMilli(); // 17356896000000
int nsTimestamp = now.getNano(); // Nanoseconds within second

System.out.println("Seconds: " + secTimestamp);
System.out.println("Milliseconds: " + msTimestamp);
System.out.println("Nanoseconds: " + nsTimestamp);

Format ISO 8601

Définition

ISO 8601 est un standard international pour représenter dates et heures. C’est le format le plus utilisé pour stocker et échanger des timestamps.

Variantes de format

Basic ISO 8601 Formats:
  1. Calendar Date: 2026-01-01
  2. Date and Time: 2026-01-01T12:00:00
  3. With Time Zone: 2026-01-01T12:00:00+08:00
  4. UTC (Z notation): 2026-01-01T12:00:00Z
  5. With Fractional Seconds: 2026-01-01T12:00:00.123Z
  6. With Milliseconds: 2026-01-01T12:00:00.123Z
  7. With Nanoseconds: 2026-01-01T12:00:00.123456789Z

Décomposition d’ISO 8601

Format: YYYY-MM-DDThh:mm:ss.sssTZD

Components:
  YYYY - Four-digit year (2026)
  MM - Two-digit month (01)
  DD - Two-digit day (01)
  T - Separator between date and time
  hh - Two-digit hour (00-23)
  mm - Two-digit minute (00-59)
  ss - Two-digit second (00-59)
  sss - Fractional seconds (optional)
  TZD - Time zone designator (Z, +08:00, -05:00)

Exemples de code : ISO 8601

// JavaScript has built-in ISO 8601 support
const now = new Date();
const isoString = now.toISOString(); // "2026-01-01T12:00:00.000Z"

// Parse ISO 8601
const date = new Date('2026-01-01T12:00:00Z');

console.log('ISO 8601:', isoString);
console.log('Parsed:', date.toISOString());
from datetime import datetime, timezone

# Generate ISO 8601
now_utc = datetime.now(timezone.utc)
iso_string = now_utc.isoformat() # "2026-01-01T12:00:00+00:00"

# Parse ISO 8601
parsed_date = datetime.fromisoformat('2026-01-01T12:00:00+00:00')

print(f'ISO 8601: {iso_string}')
print(f'Parsed: {parsed_date.isoformat()}')
import java.time.Instant;
import java.time.format.DateTimeFormatter;

// Generate ISO 8601
Instant now = Instant.now();
String isoString = now.toString(); // "2026-01-01T12:00:00:00Z"

// Parse ISO 8601
Instant parsed = Instant.parse("2026-01-01T12:00:00:00Z");

System.out.println("ISO 8601: " + isoString);
System.out.println("Parsed: " + parsed);

Format RFC 3339

Définition

RFC 3339 est un sous-ensemble d’ISO 8601 conçu pour les protocoles internet et les standards d’email.

Différences avec ISO 8601

CaractéristiqueISO 8601RFC 3339
FormatPlusieurs variantesFormat fixe
Fuseau horaireOffset ou ZOffset ou Z
ApplicationsUsage généralProtocoles internet (HTTP, email)
Secondes fractionnellesOptionnellesOptionnelles
Exemple2026-01-01T12:00:00+08:002026-01-01T12:00:00+08:00

Note : RFC 3339 est presque identique à ISO 8601. En pratique, ils sont souvent utilisés de façon interchangeable.

Exemples de code : RFC 3339

// RFC 3339 is similar to ISO 8601
const now = new Date();
const rfc3339String = now.toISOString(); // "2026-01-01T12:00:00.000Z"

// RFC 3339 commonly used in HTTP headers
const httpDate = now.toUTCString(); // "Wed, 01 Jan 2026 12:00:00 GMT"

console.log('RFC 3339:', rfc3339String);
console.log('HTTP Date:', httpDate);
from datetime import datetime, timezone
import email.utils

# Generate RFC 3339 (same as ISO 8601)
now_utc = datetime.now(timezone.utc)
rfc3339_string = now_utc.isoformat() # "2026-01-01T12:00:00+00:00"

# Generate HTTP date format
http_date = email.utils.format_datetime(now_utc)

print(f'RFC 3339: {rfc3339_string}')
print(f'HTTP Date: {http_date}')

Conversion de formats

Unix Timestamp ↔ ISO 8601

// Unix to ISO 8601
function unixToIso(unixTimestamp, precision = 'ms') {
  let ts = unixTimestamp;
  if (precision === 's') {
    ts = unixTimestamp * 1000;
  } else if (precision === 'us') {
    ts = unixTimestamp / 1000;
  } else if (precision === 'ns') {
    ts = unixTimestamp / 1000;
  } else if (precision === 'ns') {
    ts = unixTimestamp / 1000000;
  }
  return new Date(ts).toISOString();
}

// ISO 8601 to Unix
function isoToUnix(isoString) {
  return Math.floor(new Date(isoString).getTime() / 1000);
}

// Examples
const unixTs = 1735689600;
const isoStr = unixToIso(unixTs); // "2026-01-01T00:00:00.000Z"
const backToUnix = isoToUnix(isoStr); // 1735689600

console.log('Unix → ISO:', isoStr);
console.log('ISO → Unix:', backToUnix);
from datetime import datetime, timezone

def unix_to_iso(unix_timestamp, precision='s'):
    """Convert Unix timestamp to ISO 8601 string"""
    ts = unix_timestamp
    if precision == 's':
        ts = unix_timestamp
    elif precision == 'ms':
        ts = unix_timestamp / 1000
    elif precision == 'us':
        ts = unix_timestamp / 1000
    elif precision == 'ns':
        ts = unix_timestamp / 1000000
    elif precision == 'ns':
        ts = unix_timestamp / 1000000000

    dt = datetime.fromtimestamp(ts, timezone.utc)
    return dt.isoformat()

def iso_to_unix(iso_string):
    """Convert ISO 8601 string to Unix timestamp"""
    dt = datetime.fromisoformat(iso_string)
    return int(dt.timestamp())

# Examples
unix_ts = 1735689600
iso_str = unix_to_iso(unix_ts)  # "2026-01-01T00:00:00+00:00"
back_to_unix = iso_to_unix(iso_str)  # 1735689600

print(f'Unix → ISO: {iso_str}')
print(f'ISO → Unix: {back_to_unix}')

Détection de précision

Détecter la précision d’un timestamp Unix

function detectPrecision(timestamp) {
  const str = timestamp.toString();

  if (str.length === 10) {
    return 'seconds';
  } else if (str.length === 13) {
    return 'milliseconds';
  } else if (str.length === 16) {
    return 'microseconds';
  } else if (str.length === 19) {
    return 'nanoseconds';
  }

  return 'unknown';
}

// Examples
console.log(detectPrecision(1735689600)); // "seconds"
console.log(detectPrecision(17356896000000)); // "milliseconds"
console.log(detectPrecision(173568960000000000)); // "microseconds"
console.log(detectPrecision(173568960000000000000)); // "nanoseconds"
def detect_precision(timestamp):
    """Detect Unix timestamp precision"""
    str_ts = str(int(timestamp))

    if len(str_ts) == 10:
        return 'seconds'
    elif len(str_ts) == 13:
        return 'milliseconds'
    elif len(str_ts) == 16:
        return 'microseconds'
    elif len(str_ts) == 19:
        return 'nanoseconds'

    return 'unknown'

# Examples
print(detect_precision(1735689600))  # "seconds"
print(detect_precision(173568960000000))  # "milliseconds"
print(detect_precision(173568960000000000))  # "microseconds"
print(detect_precision(173568960000000000000))  # "nanoseconds"

Tableau comparatif

Unix Timestamp vs ISO 8601 vs RFC 3339

AspectUnix TimestampISO 8601RFC 3339
FormatNombre (entier/float)ChaîneChaîne
LisibleNonOuiOui
Info fuseauNon (UTC implicite)Oui (optionnel)Oui (optionnel)
PrécisionConfigurableConfigurableConfigurable
Taille4-8 octets20-30 octets20-30 octets
Support DBUniverselUniverselUniversel
Usage courantTimestamps systèmeAPIs, JSON, DBHTTP, email, APIs
Exemple17356896002026-01-01T12:00:00:00Z2026-01-01T12:00:00:00Z

Recommandation : utilisez les timestamps Unix pour le stockage interne et les calculs. Utilisez ISO 8601/RFC 3339 pour les APIs, l’échange de données et les formats lisibles.

Bonnes pratiques

Stockage

  1. Utiliser les timestamps Unix pour un stockage et une indexation efficaces
  2. Utiliser ISO 8601 pour les APIs externes et l’échange de données
  3. Toujours inclure le fuseau lors de l’affichage
  4. Documenter le format dans le schéma
-- Best practice: Store Unix timestamp in database
CREATE TABLE events (
  id INT PRIMARY KEY,
  event_timestamp BIGINT,  -- Unix timestamp in milliseconds
  description TEXT,
  created_at TIMESTAMP WITHOUT TIME ZONE DEFAULT NOW()
);

Réponses d’API

  1. Utiliser ISO 8601 dans les réponses
  2. Inclure le timestamp Unix pour l’accès programmatique
  3. Spécifier clairement le fuseau horaire
{
  "event": {
    "id": 123,
    "timestamp": 173568960000000,
    "iso8601": "2026-01-01T12:00:00:00Z",
    "timezone": "UTC",
    "human_readable": "January 1, 2026 at 12:00:00 AM UTC"
  }
}

Gestion des erreurs

  1. Valider le format avant parsing
  2. Gérer les secondes intercalaires pour les applis haute précision
  3. Dégradation contrôlée pour les formats inconnus
// Validate ISO 8601 format
function isValidISO8601(str) {
  const isoRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2}:\d{2})?$/;
  return isoRegex.test(str);
}

// Handle parsing errors
function safeParseISO8601(str) {
  try {
    return new Date(str);
  } catch (error) {
    console.error('Invalid ISO 8601 format:', str);
    return new Date(); // Fallback to current time
  }
}

Pièges fréquents

Piège 1 : supposer que Unix est toujours en secondes

// ❌ Wrong: Always dividing by 1000
const timestamp = Date.now();
const wrongDate = new Date(timestamp / 1000); // Incorrect division

// ✅ Right: Check precision first
const date = new Date(timestamp); // Date accepts milliseconds directly

Piège 2 : ignorer les fuseaux horaires

// ❌ Wrong: Creating local time without timezone
const localTime = new Date('2026-01-01T12:00:00'); // Ambiguous

// ✅ Right: Specify timezone explicitly
const utcTime = new Date('2026-01-01T12:00:00Z'); // Clear UTC
const tokyoTime = new Date('2026-01-01T12:00:00+09:00'); // Tokyo time

Piège 3 : mélanger les formats

// ❌ Wrong: Inconsistent formats in API
{
  "timestamp": 1735689600,
  "date": "01/01/2026",
  "time": "12:00 PM",
  "datetime": "2026-01-01 12:00"
}

// ✅ Right: Consistent ISO 8601 format
{
  "timestamp": 1735689600,
  "iso8601": "2026-01-01T12:00:00:00Z",
  "timezone": "UTC"
}

Outils associés

FAQ

Q : Quelle est la différence entre ISO 8601 et RFC 3339 ?

R : RFC 3339 est un sous-ensemble d’ISO 8601 pour les protocoles internet. En pratique ils sont très proches, mais RFC 3339 est plus strict.

Q : Comment savoir si un timestamp Unix est en secondes ou millisecondes ?

R : Comptez les chiffres : 10 = secondes, 13 = millisecondes. Vous pouvez aussi vérifier l’année.

Q : Quelle précision utiliser ?

R : Millisecondes pour les applis web (par défaut en JavaScript), secondes pour l’efficacité en base, micro/nanosecondes pour la haute précision.

Q : ISO 8601 supporte‑t‑il les fuseaux horaires ?

R : Oui, offsets (+08:00) et notation Z pour UTC.

Q : Comment gérer les fuseaux avec des timestamps Unix ?

R : Les timestamps Unix sont toujours en UTC. Convertissez en heure locale uniquement à l’affichage.

Q : Quelle est la valeur maximale d’un timestamp Unix ?

R : Sur 64 bits, le problème de 2038 n’est pas bloquant. Le maximum théorique est très loin dans le futur.