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.
TEXT1Unix Epoch Reference: 2 Start Date: January 1, 1970, 00:00:00 UTC 3 Current: January 1, 2026, 00:00:00 UTC 4 Timestamp: 1735689600 (seconds)
Niveaux de précision
| Précision | Exemple | Magnitude | Usage courant |
|---|---|---|---|
| Secondes | 1735689600 | 10 chiffres | Systèmes Unix/Linux |
| Millisecondes | 17356896000000 | 13 chiffres | JavaScript, APIs web |
| Microsecondes | 173568960000000000 | 16 chiffres | Mesure haute précision |
| Nanosecondes | 173568960000000000000 | 19 chiffres | Calcul scientifique |
Exemples de code : différentes précisions
JAVASCRIPT1// JavaScript uses milliseconds by default 2const msTimestamp = Date.now(); // 17356896000000 3const secTimestamp = Math.floor(Date.now() / 1000); // 1735689600 4const nsTimestamp = Date.now() * 1000000; // 173568960000000000000 5 6console.log('Milliseconds:', msTimestamp); 7console.log('Seconds:', secTimestamp); 8console.log('Nanoseconds:', nsTimestamp);
PYTHON1from datetime import datetime 2import time 3 4# Python supports multiple precisions 5now = datetime.now(datetime.timezone.utc) 6sec_timestamp = int(now.timestamp()) 7ms_timestamp = int(now.timestamp() * 1000) 8us_timestamp = int(now.timestamp() * 1000000) 9ns_timestamp = int(now.timestamp() * 1000000000) 10 11print(f'Seconds: {sec_timestamp}') 12print(f'Milliseconds: {ms_timestamp}') 13print(f'Microseconds: {us_timestamp}') 14print(f'Nanoseconds: {ns_timestamp}')
JAVA1import java.time.Instant; 2 3// Java supports multiple precisions 4Instant now = Instant.now(); 5long secTimestamp = now.getEpochSecond(); // 1735689600 6long msTimestamp = now.toEpochMilli(); // 17356896000000 7int nsTimestamp = now.getNano(); // Nanoseconds within second 8 9System.out.println("Seconds: " + secTimestamp); 10System.out.println("Milliseconds: " + msTimestamp); 11System.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
TEXT1Basic ISO 8601 Formats: 2 1. Calendar Date: 2026-01-01 3 2. Date and Time: 2026-01-01T12:00:00 4 3. With Time Zone: 2026-01-01T12:00:00+08:00 5 4. UTC (Z notation): 2026-01-01T12:00:00Z 6 5. With Fractional Seconds: 2026-01-01T12:00:00.123Z 7 6. With Milliseconds: 2026-01-01T12:00:00.123Z 8 7. With Nanoseconds: 2026-01-01T12:00:00.123456789Z
Décomposition d’ISO 8601
TEXT1Format: YYYY-MM-DDThh:mm:ss.sssTZD 2 3Components: 4 YYYY - Four-digit year (2026) 5 MM - Two-digit month (01) 6 DD - Two-digit day (01) 7 T - Separator between date and time 8 hh - Two-digit hour (00-23) 9 mm - Two-digit minute (00-59) 10 ss - Two-digit second (00-59) 11 sss - Fractional seconds (optional) 12 TZD - Time zone designator (Z, +08:00, -05:00)
Exemples de code : ISO 8601
JAVASCRIPT1// JavaScript has built-in ISO 8601 support 2const now = new Date(); 3const isoString = now.toISOString(); // "2026-01-01T12:00:00.000Z" 4 5// Parse ISO 8601 6const date = new Date('2026-01-01T12:00:00Z'); 7 8console.log('ISO 8601:', isoString); 9console.log('Parsed:', date.toISOString());
PYTHON1from datetime import datetime, timezone 2 3# Generate ISO 8601 4now_utc = datetime.now(timezone.utc) 5iso_string = now_utc.isoformat() # "2026-01-01T12:00:00+00:00" 6 7# Parse ISO 8601 8parsed_date = datetime.fromisoformat('2026-01-01T12:00:00+00:00') 9 10print(f'ISO 8601: {iso_string}') 11print(f'Parsed: {parsed_date.isoformat()}')
JAVA1import java.time.Instant; 2import java.time.format.DateTimeFormatter; 3 4// Generate ISO 8601 5Instant now = Instant.now(); 6String isoString = now.toString(); // "2026-01-01T12:00:00:00Z" 7 8// Parse ISO 8601 9Instant parsed = Instant.parse("2026-01-01T12:00:00:00Z"); 10 11System.out.println("ISO 8601: " + isoString); 12System.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éristique | ISO 8601 | RFC 3339 |
|---|---|---|
| Format | Plusieurs variantes | Format fixe |
| Fuseau horaire | Offset ou Z | Offset ou Z |
| Applications | Usage général | Protocoles internet (HTTP, email) |
| Secondes fractionnelles | Optionnelles | Optionnelles |
| Exemple | 2026-01-01T12:00:00+08:00 | 2026-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
JAVASCRIPT1// RFC 3339 is similar to ISO 8601 2const now = new Date(); 3const rfc3339String = now.toISOString(); // "2026-01-01T12:00:00.000Z" 4 5// RFC 3339 commonly used in HTTP headers 6const httpDate = now.toUTCString(); // "Wed, 01 Jan 2026 12:00:00 GMT" 7 8console.log('RFC 3339:', rfc3339String); 9console.log('HTTP Date:', httpDate);
PYTHON1from datetime import datetime, timezone 2import email.utils 3 4# Generate RFC 3339 (same as ISO 8601) 5now_utc = datetime.now(timezone.utc) 6rfc3339_string = now_utc.isoformat() # "2026-01-01T12:00:00+00:00" 7 8# Generate HTTP date format 9http_date = email.utils.format_datetime(now_utc) 10 11print(f'RFC 3339: {rfc3339_string}') 12print(f'HTTP Date: {http_date}')
Conversion de formats
Unix Timestamp ↔ ISO 8601
JAVASCRIPT1// Unix to ISO 8601 2function unixToIso(unixTimestamp, precision = 'ms') { 3 let ts = unixTimestamp; 4 if (precision === 's') { 5 ts = unixTimestamp * 1000; 6 } else if (precision === 'us') { 7 ts = unixTimestamp / 1000; 8 } else if (precision === 'ns') { 9 ts = unixTimestamp / 1000; 10 } else if (precision === 'ns') { 11 ts = unixTimestamp / 1000000; 12 } 13 return new Date(ts).toISOString(); 14} 15 16// ISO 8601 to Unix 17function isoToUnix(isoString) { 18 return Math.floor(new Date(isoString).getTime() / 1000); 19} 20 21// Examples 22const unixTs = 1735689600; 23const isoStr = unixToIso(unixTs); // "2026-01-01T00:00:00.000Z" 24const backToUnix = isoToUnix(isoStr); // 1735689600 25 26console.log('Unix → ISO:', isoStr); 27console.log('ISO → Unix:', backToUnix);
PYTHON1from datetime import datetime, timezone 2 3def unix_to_iso(unix_timestamp, precision='s'): 4 """Convert Unix timestamp to ISO 8601 string""" 5 ts = unix_timestamp 6 if precision == 's': 7 ts = unix_timestamp 8 elif precision == 'ms': 9 ts = unix_timestamp / 1000 10 elif precision == 'us': 11 ts = unix_timestamp / 1000 12 elif precision == 'ns': 13 ts = unix_timestamp / 1000000 14 elif precision == 'ns': 15 ts = unix_timestamp / 1000000000 16 17 dt = datetime.fromtimestamp(ts, timezone.utc) 18 return dt.isoformat() 19 20def iso_to_unix(iso_string): 21 """Convert ISO 8601 string to Unix timestamp""" 22 dt = datetime.fromisoformat(iso_string) 23 return int(dt.timestamp()) 24 25# Examples 26unix_ts = 1735689600 27iso_str = unix_to_iso(unix_ts) # "2026-01-01T00:00:00+00:00" 28back_to_unix = iso_to_unix(iso_str) # 1735689600 29 30print(f'Unix → ISO: {iso_str}') 31print(f'ISO → Unix: {back_to_unix}')
Détection de précision
Détecter la précision d’un timestamp Unix
JAVASCRIPT1function detectPrecision(timestamp) { 2 const str = timestamp.toString(); 3 4 if (str.length === 10) { 5 return 'seconds'; 6 } else if (str.length === 13) { 7 return 'milliseconds'; 8 } else if (str.length === 16) { 9 return 'microseconds'; 10 } else if (str.length === 19) { 11 return 'nanoseconds'; 12 } 13 14 return 'unknown'; 15} 16 17// Examples 18console.log(detectPrecision(1735689600)); // "seconds" 19console.log(detectPrecision(17356896000000)); // "milliseconds" 20console.log(detectPrecision(173568960000000000)); // "microseconds" 21console.log(detectPrecision(173568960000000000000)); // "nanoseconds"
PYTHON1def detect_precision(timestamp): 2 """Detect Unix timestamp precision""" 3 str_ts = str(int(timestamp)) 4 5 if len(str_ts) == 10: 6 return 'seconds' 7 elif len(str_ts) == 13: 8 return 'milliseconds' 9 elif len(str_ts) == 16: 10 return 'microseconds' 11 elif len(str_ts) == 19: 12 return 'nanoseconds' 13 14 return 'unknown' 15 16# Examples 17print(detect_precision(1735689600)) # "seconds" 18print(detect_precision(173568960000000)) # "milliseconds" 19print(detect_precision(173568960000000000)) # "microseconds" 20print(detect_precision(173568960000000000000)) # "nanoseconds"
Tableau comparatif
Unix Timestamp vs ISO 8601 vs RFC 3339
| Aspect | Unix Timestamp | ISO 8601 | RFC 3339 |
|---|---|---|---|
| Format | Nombre (entier/float) | Chaîne | Chaîne |
| Lisible | Non | Oui | Oui |
| Info fuseau | Non (UTC implicite) | Oui (optionnel) | Oui (optionnel) |
| Précision | Configurable | Configurable | Configurable |
| Taille | 4-8 octets | 20-30 octets | 20-30 octets |
| Support DB | Universel | Universel | Universel |
| Usage courant | Timestamps système | APIs, JSON, DB | HTTP, email, APIs |
| Exemple | 1735689600 | 2026-01-01T12:00:00:00Z | 2026-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
- Utiliser les timestamps Unix pour un stockage et une indexation efficaces
- Utiliser ISO 8601 pour les APIs externes et l’échange de données
- Toujours inclure le fuseau lors de l’affichage
- Documenter le format dans le schéma
SQL1-- Best practice: Store Unix timestamp in database 2CREATE TABLE events ( 3 id INT PRIMARY KEY, 4 event_timestamp BIGINT, -- Unix timestamp in milliseconds 5 description TEXT, 6 created_at TIMESTAMP WITHOUT TIME ZONE DEFAULT NOW() 7);
Réponses d’API
- Utiliser ISO 8601 dans les réponses
- Inclure le timestamp Unix pour l’accès programmatique
- Spécifier clairement le fuseau horaire
JSON1{ 2 "event": { 3 "id": 123, 4 "timestamp": 173568960000000, 5 "iso8601": "2026-01-01T12:00:00:00Z", 6 "timezone": "UTC", 7 "human_readable": "January 1, 2026 at 12:00:00 AM UTC" 8 } 9}
Gestion des erreurs
- Valider le format avant parsing
- Gérer les secondes intercalaires pour les applis haute précision
- Dégradation contrôlée pour les formats inconnus
JAVASCRIPT1// Validate ISO 8601 format 2function isValidISO8601(str) { 3 const isoRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2}:\d{2})?$/; 4 return isoRegex.test(str); 5} 6 7// Handle parsing errors 8function safeParseISO8601(str) { 9 try { 10 return new Date(str); 11 } catch (error) { 12 console.error('Invalid ISO 8601 format:', str); 13 return new Date(); // Fallback to current time 14 } 15}
Pièges fréquents
Piège 1 : supposer que Unix est toujours en secondes
JAVASCRIPT1// ❌ Wrong: Always dividing by 1000 2const timestamp = Date.now(); 3const wrongDate = new Date(timestamp / 1000); // Incorrect division 4 5// ✅ Right: Check precision first 6const date = new Date(timestamp); // Date accepts milliseconds directly
Piège 2 : ignorer les fuseaux horaires
JAVASCRIPT1// ❌ Wrong: Creating local time without timezone 2const localTime = new Date('2026-01-01T12:00:00'); // Ambiguous 3 4// ✅ Right: Specify timezone explicitly 5const utcTime = new Date('2026-01-01T12:00:00Z'); // Clear UTC 6const tokyoTime = new Date('2026-01-01T12:00:00+09:00'); // Tokyo time
Piège 3 : mélanger les formats
JAVASCRIPT1// ❌ Wrong: Inconsistent formats in API 2{ 3 "timestamp": 1735689600, 4 "date": "01/01/2026", 5 "time": "12:00 PM", 6 "datetime": "2026-01-01 12:00" 7} 8 9// ✅ Right: Consistent ISO 8601 format 10{ 11 "timestamp": 1735689600, 12 "iso8601": "2026-01-01T12:00:00:00Z", 13 "timezone": "UTC" 14}
Outils associés
- Unix Timestamp Converter - Convertir entre timestamps Unix et dates avec détection automatique de précision
- ISO 8601 Converter - Convertir vers/depuis ISO 8601
- RFC 3339 Converter - Travailler avec le format RFC 3339
- Current Timestamp - Heure actuelle avec plusieurs formats et précisions
- Timestamp Validator - Valider et détecter les formats de timestamp
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.