🕐
← ガむド䞀芧に戻る

プログラミング蚀語で 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-tz や Luxon のようなラむブラリが掚奚されたす。

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 タむムスタンプ倉換ツヌル は、すばやい確認ずデバッグに信頌できる頌もしいツヌルです。

プログラミング蚀語で Unix タむムスタンプを扱う - CoolTool