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.