コード上で日付を Epoch に変換する場面
ほとんどのアプリはタイムスタンプを Unix 整数で保存しますが、入力として受け取る日付は文字列です — フォームのカレンダー値、CSV の日付列、特定タイムゾーンでフォーマットされた webhook フィールドなど。これらをコードで epoch に変換することで、DB がソートでき、サービスが比較でき、API が受け入れられるようになります。本記事では JavaScript、Python、SQL、Go、シェルそれぞれの定石と、どのチームもいずれ踏むタイムゾーンのバグを紹介します。
JavaScript:Date、getTime、ゾーン付き入力
JavaScript は時間をミリ秒で保持します。Date.UTC は UTC の壁時計時刻からミリ秒 epoch を返し、明示オフセット付きの ISO 8601 文字列は new Date(iso).getTime() で扱えます。秒にするには 1000 で割ります。
- Date.UTC(2026, 0, 1, 0, 0, 0) → 1767225600000 (month is zero-indexed)
- new Date('2026-01-01T08:00:00-05:00').getTime() → 1767265200000
- Math.floor(Date.now() / 1000) → current Unix seconds
- Wall-clock in a non-UTC zone needs a zone-aware library (Luxon, date-fns-tz, Temporal)
Python:datetime.timestamp と calendar.timegm
Python の datetime オブジェクトは .timestamp() で epoch に変換できますが、タイムゾーン付きの場合に限ります。naive な datetime はホストのローカルタイムとして解釈され、これは本番で epoch がずれる最も一般的な原因です。
- datetime(2026, 1, 1, tzinfo=timezone.utc).timestamp() → 1767225600.0
- calendar.timegm(struct_time) → seconds (UTC-only)
- datetime.now(ZoneInfo('America/New_York')).timestamp() → zone-aware now
- Avoid datetime.fromisoformat(s).timestamp() when s has no offset
SQL:EXTRACT EPOCH、UNIX_TIMESTAMP、UNIX_SECONDS
主要な DB はすべてタイムスタンプ列から epoch 整数を取り出す関数を持ちます。列のタイムゾーンを明示的に扱ってください:TIMESTAMP WITH TIME ZONE と TIMESTAMP WITHOUT TIME ZONE では挙動が大きく異なります。
- PostgreSQL: EXTRACT(EPOCH FROM ts) → seconds (double)
- MySQL: UNIX_TIMESTAMP(ts) → seconds, naive ts read in session timezone
- BigQuery: UNIX_SECONDS(ts) / UNIX_MILLIS(ts) — TIMESTAMP only
- SQLite: strftime('%s', ts) → seconds as string, cast to integer
Go とシェル:time.Unix と date +%s
Go ではオフセットを含むレイアウトでパースしてから .Unix() で秒、.UnixMilli() でミリ秒を取ります。シェルでは GNU date -d が一般的な日付文字列を解釈し、BSD / macOS の date -j -f は明示フォーマットが必要です。
- Go: t, _ := time.Parse(time.RFC3339, "2026-01-01T00:00:00Z"); t.Unix()
- Go: time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC).Unix()
- GNU date: date -d "2026-01-01 00:00:00 UTC" +%s
- macOS date: date -j -u -f "%Y-%m-%d %H:%M:%S" "2026-01-01 00:00:00" +%s
FAQ
- How do I convert time to epoch time?
- Choose the date, clock time, and timezone, then convert that instant to Unix seconds or milliseconds. If the timezone is missing, the result may be off by hours.
- Is timestamp to epoch the same as date to epoch?
- Usually yes. It means converting a readable timestamp or date-time string into an epoch number.
- Should I send epoch seconds or milliseconds to an API?
- Follow the API documentation. If it says Unix timestamp, it often means seconds, but JavaScript-oriented APIs may expect milliseconds.
- Why does the same date give a different epoch in different timezones?
- Because a local wall-clock time only identifies an instant once a timezone is attached. 2026-01-01 00:00 is 1767225600 in UTC but 1767243600 in New York — five hours later in real time. Set the timezone before converting.