Guide

타임스탬프 형식 이해

소개

타임스탬프는 다양한 형식과 정밀도로 제공됩니다. 시간 데이터, API, 데이터베이스 및 분산 시스템을 다루는 개발자에게는 이러한 형식을 이해하는 것이 중요합니다.

간략한 요약: Unix 타임스탬프(초, 밀리초, 마이크로초, 나노초), ISO 8601 문자열 및 RFC 3339 형식이 가장 일반적입니다. 각각은 소프트웨어 개발에서 서로 다른 목적을 수행합니다.

유닉스 타임스탬프 형식

유닉스 에포크(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자리유닉스/리눅스 시스템
밀리초1735689600000013자리자바스크립트, 웹 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과의 차이점

기능ISO 8601RFC 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}')

형식 변환

유닉스 타임스탬프 ⇔ 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"

비교표

유닉스 타임스탬프 vs ISO 8601 vs RFC 3339

측면유닉스 타임스탬프ISO 8601RFC 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"
}

관련 도구

FAQ

Q: ISO 8601과 RFC 3339의 차이점은 무엇인가요?

A: RFC 3339는 인터넷 프로토콜용으로 설계된 ISO 8601의 하위 집합입니다. 실제로는 거의 동일하지만 RFC 3339에는 더 엄격한 형식 규칙이 있습니다.

질문: Unix 타임스탬프가 초 단위인지 밀리초 단위인지 어떻게 알 수 있나요?

A: 숫자 계산: 10자리 = 초, 13자리 = 밀리초. 연도도 확인할 수 있습니다(초 = 1970+, 밀리초 = 1970+).

Q: 애플리케이션에 어떤 정밀도를 사용해야 합니까?

A: 일반 웹 애플리케이션(JavaScript 기본값)에는 밀리초를 사용하고, 데이터베이스 저장 효율성을 위해서는 초를 사용하고, 고정밀 타이밍에는 마이크로초/나노초를 사용하세요.

질문: ISO 8601은 시간대를 지원합니까?

A: 예, ISO 8601은 시간대 오프셋(+08:00)과 UTC에 대한 Z 표기법을 지원합니다.

질문: Unix 타임스탬프를 사용하여 시간대를 어떻게 처리하나요?

A: Unix 타임스탬프는 항상 UTC입니다. 시간대 설정을 사용하여 사용자에게 표시할 때만 현지 시간으로 변환합니다.

Q: Unix 타임스탬프의 최대 값은 무엇입니까?

A: 64비트 시스템의 경우: 2038년 1월 19일(2038년 문제)은 문제가 되지 않습니다. 이론상 최대치는 수십억 년 후의 미래입니다.