Skip to main content
DevTool House
Back to Blogs
Developer Guides

How to Convert a Unix Timestamp to a Date (JavaScript, Python, SQL)

One-line conversions for JavaScript, Python, MySQL, PostgreSQL, SQLite and MongoDB, plus the seconds, milliseconds and time zone bugs to avoid.

By Wali UllahDecember 3, 20266 min read
A flip clock showing the Unix timestamp 1700000000 next to a calendar

A Unix timestamp is the number of seconds since 1 January 1970, 00:00:00 UTC. To turn it into a date, you need to know two things before you write any code: is it in seconds or milliseconds, and which time zone should the date be shown in. Get those right and the conversion is one line in any language. Get them wrong and you get dates in 1970, dates in the year 55,000, or times that are five hours off.

Below is the one-liner for JavaScript, Python, MySQL, PostgreSQL, SQLite and MongoDB, plus the mistakes I see most often. To check a value quickly without code, paste it into the Timestamp Converter. It detects seconds versus milliseconds automatically and shows the result in UTC and in your own time zone.

Seconds or milliseconds? Count the digits

Digits (today) Unit Typical source Example
10 seconds Unix tools, PHP, Python's time.time(), JWT exp and iat, most APIs 1700000000
13 milliseconds JavaScript Date.now(), Java, MongoDB dates in JSON 1700000000000
16 microseconds PostgreSQL internals, some Python libraries, analytics exports 1700000000000000
19 nanoseconds Go's UnixNano(), some logging systems 1700000000000000000

All four examples are the same instant: 14 November 2023, 22:13:20 UTC.

If a converted date shows 1970, you probably treated milliseconds as seconds the wrong way round (or the value was 0). If it shows a year in the tens of thousands, you treated a millisecond, microsecond or nanosecond value as seconds.

JavaScript

JavaScript dates work in milliseconds, so multiply seconds by 1000:

const seconds = 1700000000;
const date = new Date(seconds * 1000);

date.toISOString();            // '2023-11-14T22:13:20.000Z' (UTC)
date.toLocaleString('en-PK', { timeZone: 'Asia/Karachi' });
// '15/11/2023, 3:13:20 am' (Pakistan time, UTC+5)

// And back: current time as a Unix timestamp in seconds
Math.floor(Date.now() / 1000);

toISOString() always gives UTC with a Z at the end, which is what I store and send in APIs. Use toLocaleString() or Intl.DateTimeFormat with an explicit timeZone only when displaying the date to a person. Without timeZone, it uses the time zone of the machine running the code, which on a server is usually UTC.

Python

from datetime import datetime, timezone
from zoneinfo import ZoneInfo

ts = 1700000000
utc = datetime.fromtimestamp(ts, tz=timezone.utc)
print(utc.isoformat())          # 2023-11-14T22:13:20+00:00

karachi = utc.astimezone(ZoneInfo("Asia/Karachi"))
print(karachi.isoformat())      # 2023-11-15T03:13:20+05:00

# And back
print(int(utc.timestamp()))     # 1700000000

Always pass tz=. Without it, datetime.fromtimestamp() returns a "naive" datetime in the machine's local time zone, and the same code gives different results on your laptop and on the server. Avoid datetime.utcfromtimestamp(): it is deprecated since Python 3.12 and also returns a naive value. zoneinfo is part of the standard library from Python 3.9.

MySQL

SELECT FROM_UNIXTIME(1700000000);
-- 2023-11-14 22:13:20 when the session time zone is UTC

SELECT UNIX_TIMESTAMP('2023-11-14 22:13:20');
-- 1700000000 (again, interpreted in the session time zone)

FROM_UNIXTIME() and UNIX_TIMESTAMP() both use the session time zone. On a server set to Pakistan time, the first query returns 2023-11-15 03:13:20. Run SELECT @@session.time_zone; when results look shifted, and set time_zone = '+00:00' on the connection if you want UTC everywhere.

PostgreSQL

SELECT to_timestamp(1700000000);
-- 2023-11-14 22:13:20+00 (a timestamptz, displayed in the session's TimeZone)

SELECT to_timestamp(1700000000) AT TIME ZONE 'Asia/Karachi';
-- 2023-11-15 03:13:20 (wall-clock time in Karachi)

SELECT EXTRACT(EPOCH FROM now())::bigint;
-- the current Unix timestamp in seconds

to_timestamp() returns a timestamptz, so the same instant displays differently depending on the session's TimeZone setting, but it is stored correctly either way. For milliseconds, divide first: to_timestamp(1700000000000 / 1000.0).

SQLite

SELECT datetime(1700000000, 'unixepoch');
-- 2023-11-14 22:13:20

SELECT datetime(1700000000, 'unixepoch', 'localtime');
-- the same instant in the machine's local time zone

SELECT strftime('%s', '2023-11-14 22:13:20');
-- '1700000000'

MongoDB and Node.js

MongoDB stores dates as milliseconds since the epoch. If an API gives you seconds, convert before saving:

// In application code (Node.js driver or Mongoose)
await orders.insertOne({ paidAt: new Date(1700000000 * 1000) });

// In an aggregation, $toDate expects milliseconds:
{ $toDate: { $multiply: ['$paidAtSeconds', 1000] } }

Every MongoDB ObjectId also contains the second it was created, so doc._id.getTimestamp() gives you a creation date even if you never stored one.

Time zones: store UTC, convert at the edge

The rule that has saved me the most debugging: store and transmit timestamps in UTC, and convert to local time only when showing them to a person. A Unix timestamp has no time zone; it is the same instant everywhere. Time zones only appear when you format it as a date.

Pakistan Standard Time is UTC+5 with no daylight saving, so 22:13 UTC is 03:13 the next morning in Karachi. That one-day jump catches people writing daily reports: an order placed at 2 a.m. in Lahore falls on the previous day in UTC. If your business day is Pakistani time, group by the date in Asia/Karachi, not by the UTC date.

The year 2038 problem

A signed 32-bit integer can count up to 2147483647 seconds, which is 19 January 2038, 03:14:07 UTC. One second later, it overflows and wraps around to 1901. Modern languages and databases use 64-bit values, but check:

  • old MySQL INT columns that store Unix seconds (use BIGINT, or a DATETIME or TIMESTAMP column instead);
  • embedded systems and old C code using 32-bit time_t;
  • MySQL's TIMESTAMP type, which only covers dates up to 2038-01-19 03:14:07 UTC. DATETIME goes to the year 9999.

Common mistakes

Symptom Cause Fix
Date shows 1970 The value was 0 or null Check the source field before converting
Date in the year 50,000+ Milliseconds or microseconds treated as seconds Divide by 1,000 or 1,000,000 first
Time off by 5 hours (or your UTC offset) UTC compared with local time Store UTC; convert only for display, with an explicit time zone
Different results on laptop and server Naive datetimes using the machine's time zone Pass tz= in Python; set timeZone in JavaScript formatting
Daily report totals do not match Grouped by UTC date, business runs on local time Group by the date in the business time zone

FAQ

How do I convert a Unix timestamp to a date in JavaScript?

new Date(seconds * 1000).toISOString() for seconds, or new Date(milliseconds) for millisecond values. Multiply by 1000 because JavaScript dates use milliseconds.

How do I know if a timestamp is in seconds or milliseconds?

Count the digits. A current timestamp in seconds has 10 digits and one in milliseconds has 13. The Timestamp Converter applies the same rule: values above 1,000,000,000,000 are read as milliseconds.

What is the current Unix timestamp?

It is the number of seconds since 1970-01-01 00:00:00 UTC, right now. In JavaScript use Math.floor(Date.now() / 1000), in Python int(time.time()), and in a terminal date +%s.

Does a Unix timestamp have a time zone?

No. A Unix timestamp always counts from midnight UTC on 1 January 1970, so it is the same everywhere. The time zone only matters when you display it as a date.

How do I convert a timestamp to Pakistan time?

Convert to a date in UTC first, then format it in the Asia/Karachi time zone, which is UTC+5 all year. For example, new Date(ts * 1000).toLocaleString('en-PK', { timeZone: 'Asia/Karachi' }) in JavaScript.

Try the related tools

Related articles