Guide

タイムスタンプ形式について

はじめに

タイムスタンプにはさまざまな形式と精度があります。これらの形式を理解することは、時刻データ、API、データベース、分散システムを扱う開発者にとって非常に重要です。

簡単な概要: Unix タイムスタンプ (秒、ミリ秒、マイクロ秒、ナノ秒)、ISO 8601 文字列、および RFC 3339 形式が最も一般的です。それぞれはソフトウェア開発において異なる目的を果たします。

Unix タイムスタンプ形式

Unix エポック (POSIX 時間)

Unix タイムスタンプは、1970 年 1 月 1 日 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)

精度レベル

精度大きさ一般的な使用
173568960010桁Unix/Linux システム
ミリ秒1735689600000013桁JavaScript、Web API
マイクロ秒17356896000000000016桁高精度タイミング
ナノ秒17356896000000000000019桁科学コンピューティング

コード例: さまざまな精度

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

ISO 8601 フォーマット

定義

ISO 8601 は、日付と時刻を表すための国際標準です。これは、タイムスタンプの保存と交換に最も広く使用されている形式です。

フォーマットのバリエーション

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

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)

コード例: 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);

RFC 3339 形式

定義

RFC 3339 は、インターネット プロトコルと電子メール標準向けに特別に設計された ISO 8601 のサブセットです。

ISO 8601との違い

特集ISO8601RFC 3339
形式複数のバリエーション固定フォーマット
タイムゾーンオフセットまたは Zを使用できます。オフセットまたは Z
アプリケーション汎用インターネット プロトコル (HTTP、電子メール)
小数秒オプションオプション
2026-01-01T12:00:00+08:002026-01-01T12:00:00+08:00

: RFC 3339 は ISO 8601 とほぼ同じです。実際には、インターネット アプリケーションでは同じ意味で使用されます。

コード例: 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}')

フォーマット変換

Unix タイムスタンプ ↔ 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}')

正確な検出

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"

比較表

Unix タイムスタンプ、ISO 8601、RFC 3339

側面Unix タイムスタンプISO8601RFC 3339
形式数値 (整数/浮動小数点)文字列文字列
人間が判読可能いいえはいはい
タイムゾーン情報いいえ (暗黙的な UTC)はい (オプション)はい (オプション)
精度設定可能設定可能設定可能
ストレージ サイズ4 ~ 8 バイト20~30バイト20~30バイト
データベースのサポートユニバーサルユニバーサルユニバーサル
一般的な用途システムのタイムスタンプAPI、JSON、データベースHTTP、電子メール、API
17356896002026-01-01T12:00:00:00Z2026-01-01T12:00:00:00Z

推奨事項: 内部ストレージと計算には Unix タイムスタンプを使用します。 API、データ交換、人間が読める形式には ISO 8601/RFC 3339 を使用します。

ベストプラクティス

ストレージ

  1. 効率的なストレージとインデックス作成のためにデータベースで Unix タイムスタンプを使用
  2. 外部 API とデータ交換には ISO 8601 を使用
  3. ユーザーに表示するときは 常にタイムゾーンを含める
  4. データベース スキーマ コメントの ドキュメント形式
-- 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()
);

API レスポンス

  1. API 応答本文には ISO 8601 を使用
  2. プログラムによるアクセスのために Unix タイムスタンプを含める
  3. 応答では タイムゾーンを明確に指定
{
  "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"
  }
}

エラー処理

  1. 解析前に 形式を検証
  2. 高精度アプリケーションでの うるう秒の処理
  3. 不明な形式の グレースフル デグラデーション
// 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
  }
}

よくある落とし穴

落とし穴 1: Unix タイムスタンプが常に秒であると仮定する

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

落とし穴 2: タイムゾーンの無視

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

落とし穴 3: フォーマットの混在

// ❌ 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"
}

関連ツール

よくある質問

Q: ISO 8601 と RFC 3339 の違いは何ですか?

A: RFC 3339 は、インターネット プロトコル用に設計された ISO 8601 のサブセットです。実際にはこれらはほぼ同じですが、RFC 3339 にはより厳密な形式規則があります。

Q: Unix タイムスタンプが秒単位であるかミリ秒単位であるかを確認するにはどうすればよいですか?

A: 桁数のカウント: 10 桁 = 秒、13 桁 = ミリ秒。年も確認できます (秒 = 1970 年以降、ミリ秒 = 1970 年以降)。

Q: アプリケーションにはどの程度の精度を使用する必要がありますか?

A: 一般的な Web アプリケーション (JavaScript のデフォルト) にはミリ秒、データベース ストレージ効率には秒、高精度のタイミングにはマイクロ秒/ナノ秒を使用します。

Q: ISO 8601 はタイムゾーンをサポートしていますか?

A: はい、ISO 8601 はタイム ゾーン オフセット (+08:00) と UTC の Z 表記をサポートしています。

Q: Unix タイムスタンプを使用してタイムゾーンを処理するにはどうすればよいですか?

A: Unix タイムスタンプは常に UTC です。タイムゾーン設定を使用してユーザーに表示する場合にのみ、現地時間に変換します。

Q: Unix タイムスタンプの最大値はどれくらいですか?

A: 64 ビット システムの場合: 2038 年 1 月 19 日 (2038 年問題) は問題になりません。理論上の最大値は数十億年先です。