🕐
← ガイド一覧に戻る

プログラミング言語で Unix タイムスタンプを扱う

· タグ: javascript, python, php, golang, programming, unix-timestamp, epoch, database

プログラミングで Unix タイムスタンプを使う理由

Unix タイムスタンプは、ソフトウェアにおける時間の共通通貨です。日付の算術演算を簡単にし(秒を加算または減算するだけ)、タイムゾーンの混乱を排除し、JSON にきれいにシリアライズできます。すべてのプログラミング言語が、これらを扱うためのわかりやすい関数を提供していますが、API は微妙に異なります。このガイドでは、最も一般的な言語とそのベストプラクティスを紹介します。

JavaScript(ブラウザと Node.js)

JavaScript は Date オブジェクトにミリ秒を使用しますが、他のほとんどのシステムは秒を使用します。これが最も一般的なバグの原因です。

現在のタイムスタンプを取得する

// Milliseconds since epoch (standard JavaScript)
const nowMs = Date.now();         // 1785292800000

// Seconds since epoch (for compatibility)
const nowSec = Math.floor(Date.now() / 1000);  // 1785292800

// Node.js high-resolution timer (microseconds)
const hrTime = process.hrtime.bigint();

タイムスタンプを日付に変換する

// From seconds (most APIs and databases)
const timestamp = 1785292800;
const date = new Date(timestamp * 1000);  // Multiply by 1000!

// From milliseconds (JavaScript native)
const dateFromMs = new Date(1785292800000);

// Format the result
console.log(date.toISOString());
// Output: 2026-07-19T00:00:00.000Z

console.log(date.toLocaleString("en-US", { timeZone: "America/New_York" }));
// Output: 7/18/2026, 8:00:00 PM

日付文字列をタイムスタンプに解析する

// Using Date.parse() (returns milliseconds)
const ms = Date.parse("2026-07-19T00:00:00Z");
const sec = ms / 1000;  // 1785292800

// Using Date constructor
const ts = Math.floor(new Date("2026-07-19 UTC").getTime() / 1000);

警告: Date.parse() の動作は、非標準の日付文字列ではブラウザ間で異なります。タイムゾーン指定子(UTC の場合は Z)を付けた ISO 8601 形式を使用するのが最も安全です。

JavaScript でタイムゾーンを扱う

// Format in a specific timezone
const date = new Date(1785292800 * 1000);
const options = {
  timeZone: "Asia/Tokyo",
  year: "numeric", month: "2-digit", day: "2-digit",
  hour: "2-digit", minute: "2-digit", second: "2-digit",
};
console.log(date.toLocaleString("ja-JP", options));
// Output: 07/19/2026 09:00:00

高度なタイムゾーン操作には、Intl.DateTimeFormat API または date-fns-tzLuxon のようなライブラリが推奨されます。

Python

Python は、タイムスタンプを扱うための低レベル(time)と高レベル(datetime)の両方のモジュールを提供します。

現在のタイムスタンプを取得する

import time

# Seconds as a float (including fractional milliseconds)
current = time.time()
# Example: 1785292800.123456

# As an integer
current_int = int(time.time())

タイムスタンプを datetime に変換する

from datetime import datetime

# UTC datetime (Python 3.x)
dt_utc = datetime.utcfromtimestamp(1785292800)

# Timezone-aware datetime (Python 3.9+ with zoneinfo)
from zoneinfo import ZoneInfo
dt_tokyo = datetime.fromtimestamp(1785292800, tz=ZoneInfo("Asia/Tokyo"))

# Formatted string
print(dt_utc.strftime("%Y-%m-%d %H:%M:%S"))
# Output: 2026-07-19 00:00:00

日付文字列をタイムスタンプに解析する

import time
from datetime import datetime

# From date string
dt = datetime.strptime("2026-07-19 00:00:00", "%Y-%m-%d %H:%M:%S")
timestamp = time.mktime(dt.timetuple())  # Treats as local time

# For UTC input
from datetime import timezone
timestamp_utc = dt.replace(tzinfo=timezone.utc).timestamp()

Pandas を扱う(データ分析)

import pandas as pd

# Convert a column of Unix timestamps to datetime
df["timestamp"] = pd.to_datetime(df["unix_seconds"], unit="s")

# Convert to different units
df["datetime_ms"] = pd.to_datetime(df["unix_milliseconds"], unit="ms")

# Set a timezone
df["timestamp_ny"] = df["timestamp"].dt.tz_localize("UTC").dt.tz_convert("America/New_York")

PHP

PHP は、タイムスタンプ操作に最もシンプルな API を備えています。

現在のタイムスタンプを取得する

<?php
$now = time();           // Integer: 1785292800
$nowMicro = microtime();  // String: "0.12345600 1785292800"
$nowFloat = microtime(true);  // Float: 1785292800.1235

タイムスタンプを日付に変換する

<?php
echo date("Y-m-d H:i:s", 1785292800);
// Output: 2026-07-19 00:00:00

// With timezone
$tz = new DateTimeZone("Europe/London");
$dt = new DateTime("@1785292800");
$dt->setTimezone($tz);
echo $dt->format("Y-m-d H:i:s");

Go

Go の time パッケージはよく設計されていますが、関わる型を明示的に理解する必要があります。

現在のタイムスタンプを取得する

package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()
    sec := now.Unix()            // int64 seconds
    milli := now.UnixMilli()     // int64 milliseconds
    nano := now.UnixNano()       // int64 nanoseconds
    fmt.Printf("Seconds: %d\n", sec)
}

タイムスタンプを日付に変換する

t := time.Unix(1785292800, 0)
fmt.Println(t.UTC())
// Output: 2026-07-19 00:00:00 +0000 UTC

// Format as string
fmt.Println(t.Format("2006-01-02 15:04:05"))
// Output: 2026-07-19 00:00:00

// With timezone
loc, _ := time.LoadLocation("America/Chicago")
fmt.Println(t.In(loc))

Rust

use std::time::{SystemTime, UNIX_EPOCH};

// Current timestamp
let now = SystemTime::now()
    .duration_since(UNIX_EPOCH)
    .expect("Time went backwards");
println!("Seconds: {}", now.as_secs());

// Timestamp to date
let dt = chrono::NaiveDateTime::from_timestamp_opt(1785292800, 0).unwrap();
println!("{}", dt.format("%Y-%m-%d %H:%M:%S"));

データベース保存: ベストプラクティス

適切なカラム型を選ぶ

| データベース | 推奨型 | 備考 | |----------|-----------------|-------| | PostgreSQL | TIMESTAMP WITH TIME ZONE または BIGINT | ネイティブのタイムスタンプ型が推奨されます | | MySQL / MariaDB | INT UNSIGNED(2106 年までの日付用)または BIGINT | TIMESTAMP 型は避けてください(範囲が 2038 年で終了します) | | SQLite | INTEGER | SQLite にはネイティブのタイムスタンプ型がありません | | MongoDB | Date オブジェクトまたは int64 | BSON Date は内部的に 64 ビットタイムスタンプです |

PostgreSQL の例

-- Store as native timestamp
CREATE TABLE events (
    id SERIAL PRIMARY KEY,
    occurred_at TIMESTAMP WITH TIME ZONE NOT NULL,
    payload JSONB
);

-- Insert with current time
INSERT INTO events (occurred_at) VALUES (NOW());

-- Query as Unix timestamp
SELECT EXTRACT(EPOCH FROM occurred_at) AS unix_ts FROM events;

MySQL の例

-- Using BIGINT for future-proof storage
CREATE TABLE logs (
    id INT AUTO_INCREMENT PRIMARY KEY,
    event_time BIGINT NOT NULL,
    message TEXT
);

-- Insert current timestamp
INSERT INTO logs (event_time, message) VALUES (UNIX_TIMESTAMP(), 'Server started');

-- Query and convert
SELECT FROM_UNIXTIME(event_time) AS readable_time FROM logs;

言語比較表

| 言語 | 現在のタイムスタンプ | タイムスタンプから日付 | 日付からタイムスタンプ | 精度 | |----------|-------------------|-------------------|-------------------|------------| | JavaScript | Date.now() | new Date(ts * 1000) | Date.parse(str) / 1000 | ミリ秒 | | Python | time.time() | datetime.fromtimestamp(ts) | datetime.strptime(str).timestamp() | 浮動小数秒 | | PHP | time() | date("Y-m-d", ts) | strtotime(str) | 秒 | | Go | time.Now().Unix() | time.Unix(ts, 0) | time.Parse(layout, str).Unix() | 秒 | | Rust | SystemTime::now() | NaiveDateTime::from_timestamp_opt() | — | 各種 |

どの言語を使う場合でも、当社の Unix タイムスタンプ変換ツール は、すばやい確認とデバッグに信頼できる頼もしいツールです。