Python の Unix タイムスタンプ スニペット

現在の Unix 時刻、タイムスタンプから datetime への変換、UTC の扱い、ミリ秒、標準ライブラリを使った整形済み日付出力を行う Python の例。

Python timestamp basics

Python's time.time() returns seconds since the Unix epoch as a floating-point number. Wrap it with int() for whole Unix seconds, or multiply by 1000 when you need milliseconds.

Timezone-aware datetime output

Use datetime.fromtimestamp(ts, tz=datetime.timezone.utc) for explicit UTC output. Avoid relying on the server's local timezone when generating values for logs, APIs, or database rows.

Python production notes

Python makes it easy to create both naive and timezone-aware datetime values, so be deliberate about which one crosses a system boundary. Use timezone-aware UTC datetimes for APIs, scheduled jobs, and database writes. Convert to a local timezone only for display, reports, or business rules that explicitly depend on a local calendar.

  • Use int(time.time()) for whole Unix seconds in scripts and command-line tools
  • Use int(time.time() * 1000) only when the receiving system expects milliseconds
  • Use datetime.fromtimestamp(ts, tz=timezone.utc) instead of local fromtimestamp for portable output
  • Use .isoformat() when you need a readable UTC value in logs or JSON

Frequently checked Python details

Does time.time() return an integer?
No. It returns seconds as a floating-point value. Wrap it with int() for whole Unix seconds, or multiply before rounding when you need milliseconds.
Should datetime values be naive or timezone-aware?
Use timezone-aware UTC datetime values for APIs, databases, and logs. Naive datetime values are best avoided at system boundaries because their timezone meaning is implicit.