WikiPlus

How to Convert Epoch Time in JavaScript and Python

JavaScript and Python are two of the most commonly used languages for web development, data science, and backend services — and both deal with Unix timestamps constantly. Despite working with the same underlying concept, the two languages handle epoch time differently in subtle ways that trip up even experienced developers. This guide provides practical, copy-paste-ready code for the most common timestamp conversion tasks in both languages.

Unix Timestamps in JavaScript: The Key Differences

JavaScript's Date object is the primary tool for working with timestamps, and its behavior has some important quirks to understand. First, JavaScript always works in milliseconds. Date.now() returns the current time as milliseconds since epoch. new Date().getTime() does the same. This means a JavaScript timestamp is always 1000 times larger than its equivalent Unix (seconds) timestamp. When you receive a seconds timestamp from an API or database, you must multiply by 1000 before passing to Date: new Date(1715500800 * 1000). Converting a timestamp to a readable string: const d = new Date(1715500800 * 1000); d.toISOString() returns '2026-05-12T00:00:00.000Z'. d.toUTCString() returns 'Mon, 12 May 2026 00:00:00 GMT'. d.toLocaleDateString() returns a date formatted for the user's locale and timezone. Converting a date string to a timestamp: new Date('2026-05-12T00:00:00Z').getTime() / 1000 gives the seconds timestamp. The division by 1000 converts milliseconds to seconds. Getting the current timestamp in seconds: Math.floor(Date.now() / 1000). For more robust timezone handling in JavaScript, the built-in Intl.DateTimeFormat API handles IANA timezone names: new Intl.DateTimeFormat('en-US', { timeZone: 'America/New_York', dateStyle: 'full', timeStyle: 'long' }).format(new Date(1715500800 * 1000)). Third-party libraries like date-fns, day.js, or Luxon provide cleaner APIs and better edge-case handling.

Unix Timestamps in Python: datetime and zoneinfo

Python's approach to timestamps is cleaner in some ways but has its own pitfalls, particularly around timezone-aware versus timezone-naive datetimes. Python's time module provides the simplest interface: import time; time.time() returns the current Unix timestamp as a float in seconds. This is the primary difference from JavaScript — Python defaults to seconds, not milliseconds. The datetime module provides rich date manipulation: from datetime import datetime, timezone. To convert a timestamp to a UTC datetime: datetime.fromtimestamp(1715500800, tz=timezone.utc). This returns a timezone-aware datetime object for May 12, 2026. Always pass tz=timezone.utc — omitting it creates a timezone-naive datetime in local time, which causes subtle bugs when the code runs in different server environments. For timezone conversion to a specific region, Python 3.9+ includes the zoneinfo module: from zoneinfo import ZoneInfo; dt_ny = datetime.fromtimestamp(1715500800, tz=ZoneInfo('America/New_York')). This handles DST transitions correctly. Converting a datetime back to a timestamp: dt.timestamp() returns a float in seconds. For an integer: int(dt.timestamp()). Parsing an ISO 8601 string: datetime.fromisoformat('2026-05-12T00:00:00+00:00'). Then .timestamp() to get the epoch value. For Python versions before 3.9, use the third-party pytz library: from pytz import timezone as tz; aware_dt = tz('America/New_York').localize(naive_dt).

Common Cross-Language Timestamp Pitfalls

When code written in JavaScript and Python needs to exchange timestamp values, several pitfalls arise. Pitfall 1: The seconds/milliseconds mismatch. Python's time.time() returns seconds. JavaScript's Date.now() returns milliseconds. When a Python backend returns a timestamp that a JavaScript frontend consumes, the JavaScript code must multiply by 1000. When JavaScript sends a timestamp to Python, Python must divide by 1000. Failing to account for this makes dates appear to be in the year 56,000 (if JS passes milliseconds to Python expecting seconds) or in 1970 (if Python passes seconds to JS without multiplying). Pitfall 2: Naive vs aware datetimes in Python. A naive datetime has no timezone info. An aware datetime has an attached timezone. Mixing them causes TypeError exceptions. Always construct datetimes with explicit timezone info when working with timestamps that may be used across systems or timezones. Pitfall 3: Floating-point precision. Python's time.time() returns a float like 1715500800.123456. Storing this as a float in a database can introduce rounding errors. Always convert to an integer (for second precision) or multiply by 1000 and convert to int (for millisecond precision) before storage. Pitfall 4: JavaScript's month indexing. new Date(2026, 4, 12) creates May 12, 2026 — month 4 is May because JavaScript months are zero-indexed (January is 0). When constructing a Date from individual components rather than a timestamp, this trips up almost every developer at least once. Pitfall 5: Implicit local time in date string parsing. new Date('2026-05-12') in JavaScript is parsed as UTC midnight, but new Date('2026-05-12T00:00:00') (without a timezone specifier) is parsed as local time in many environments. Always include the Z suffix for UTC or an explicit offset.

Quick Reference: Essential Timestamp Code Snippets

Here is a quick-reference collection of the most commonly needed timestamp operations in both languages. JavaScript — Get current timestamp in seconds: Math.floor(Date.now() / 1000) JavaScript — Convert seconds timestamp to ISO string: new Date(ts * 1000).toISOString() JavaScript — Convert date string to seconds timestamp: Math.floor(new Date('2026-05-12T00:00:00Z').getTime() / 1000) JavaScript — Format in specific timezone: new Intl.DateTimeFormat('en-US', {timeZone: 'Europe/Berlin', dateStyle: 'medium', timeStyle: 'short'}).format(new Date(ts * 1000)) Python — Get current timestamp in seconds: import time; int(time.time()) Python — Convert timestamp to UTC datetime: from datetime import datetime, timezone; datetime.fromtimestamp(ts, tz=timezone.utc) Python — Convert timestamp to specific timezone: from zoneinfo import ZoneInfo; datetime.fromtimestamp(ts, tz=ZoneInfo('Europe/Berlin')) Python — Convert datetime to timestamp: int(dt.timestamp()) Python — Parse ISO 8601 string: datetime.fromisoformat('2026-05-12T00:00:00+00:00') For interactive conversions without writing code, our online Unix Timestamp Converter handles all these cases through a simple UI — useful for quick checks during development and debugging.

Frequently Asked Questions

Why does new Date() in JavaScript work in milliseconds instead of seconds?
JavaScript was designed in the mid-1990s with millisecond precision to support animations and UI timing in browsers, where sub-second precision mattered. The Unix convention of using seconds was a server-side concept. When JavaScript needed to represent time, the designers chose milliseconds for finer granularity. This means every JavaScript timestamp is 1000x larger than the equivalent Unix seconds timestamp, which is a constant source of cross-language confusion.
What is the safest way to store timestamps in a Python application?
Store timestamps as integer seconds (or integer milliseconds for sub-second precision) in UTC. Use int(datetime.now(timezone.utc).timestamp()) to get the current UTC timestamp as an integer. Avoid storing naive datetimes or floats. For databases, use a BIGINT column for timestamps rather than a DATETIME column — it is more portable and avoids database-specific timezone handling quirks.
How do I compare timestamps across JavaScript and Python?
Normalize to the same unit before comparing. If Python gives you an int in seconds and JavaScript gives you milliseconds, either multiply the Python value by 1000 or divide the JavaScript value by 1000 before comparing. Comparing 1715500800 (seconds) against 1715500800000 (milliseconds) will always return the wrong result. The easiest approach is to standardize on seconds throughout your system and convert at the JavaScript boundary.