DevToolBoxGRATIS
Blogg

Unix Timestamp till datum: Konvertera i JavaScript, Python, Bash, SQL

7 min läsningby DevToolBox

A Unix timestamp (also called Epoch time or POSIX time) is one of the most universal ways to represent a point in time in computing. This comprehensive guide shows you how to convert Unix timestamps to human-readable dates in JavaScript, Python, Bash, SQL, PHP, and Go with ready-to-copy code examples.

Try our Unix Timestamp Converter tool

1. What Is a Unix Timestamp?

A Unix timestamp is the number of seconds that have elapsed since January 1, 1970, 00:00:00 UTC (known as the Unix Epoch). It is a single integer that unambiguously represents a moment in time, regardless of timezone.

Some systems (notably JavaScript and Java) use milliseconds since the epoch instead of seconds. A millisecond timestamp is 1000x larger, for example: 1700000000 (seconds) vs 1700000000000 (milliseconds).

Key properties: Unix timestamps are always in UTC, always integers (or floats for sub-second precision), and always count from the same epoch. Negative values represent dates before 1970.

Unix Epoch:  January 1, 1970 00:00:00 UTC
Timestamp:   0

Current:     ~1700000000  (November 2023)
             = 1,700,000,000 seconds since epoch

In milliseconds: 1700000000000  (13 digits)
In seconds:      1700000000     (10 digits)

2. JavaScript: new Date(), toISOString(), Intl.DateTimeFormat

JavaScript's Date constructor accepts milliseconds since epoch. If you have a Unix timestamp in seconds, multiply by 1000 first.

Basic conversion (seconds to date)

const timestamp = 1700000000; // seconds

// Convert to Date object (multiply by 1000 for milliseconds)
const date = new Date(timestamp * 1000);

console.log(date);
// Tue Nov 14 2023 22:13:20 GMT+0000 (UTC)

console.log(date.toUTCString());
// "Tue, 14 Nov 2023 22:13:20 GMT"

console.log(date.toLocaleDateString());
// "11/14/2023" (varies by locale)

ISO 8601 string

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

console.log(date.toISOString());
// "2023-11-14T22:13:20.000Z"

// Parse back to timestamp
const parsed = Date.parse("2023-11-14T22:13:20.000Z");
console.log(parsed / 1000);
// 1700000000

Locale-aware formatting with Intl.DateTimeFormat

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

// US English
const usFormat = new Intl.DateTimeFormat('en-US', {
  dateStyle: 'full',
  timeStyle: 'long',
  timeZone: 'America/New_York'
}).format(date);
// "Tuesday, November 14, 2023 at 5:13:20 PM EST"

// Japanese
const jpFormat = new Intl.DateTimeFormat('ja-JP', {
  dateStyle: 'full',
  timeStyle: 'long',
  timeZone: 'Asia/Tokyo'
}).format(date);
// "2023年11月15日水曜日 7:13:20 JST"

// Chinese
const cnFormat = new Intl.DateTimeFormat('zh-CN', {
  year: 'numeric', month: '2-digit', day: '2-digit',
  hour: '2-digit', minute: '2-digit', second: '2-digit',
  timeZone: 'Asia/Shanghai'
}).format(date);
// "2023/11/15 06:13:20"

Extract individual date parts

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

const year   = date.getUTCFullYear();  // 2023
const month  = date.getUTCMonth() + 1; // 11 (0-indexed, so +1)
const day    = date.getUTCDate();       // 14
const hours  = date.getUTCHours();      // 22
const mins   = date.getUTCMinutes();    // 13
const secs   = date.getUTCSeconds();    // 20

// Get current timestamp
const now = Math.floor(Date.now() / 1000);

3. Python: datetime.fromtimestamp(), Timezone-Aware

Python's datetime module provides clean timestamp conversion. Always use timezone-aware methods to avoid ambiguity.

Basic conversion

from datetime import datetime

timestamp = 1700000000

# Basic conversion (returns local time!)
dt = datetime.fromtimestamp(timestamp)
print(dt)
# 2023-11-14 22:13:20 (in your local timezone)

# Format as string
print(dt.strftime("%Y-%m-%d %H:%M:%S"))
# "2023-11-14 22:13:20"

Timezone-aware (recommended)

from datetime import datetime, timezone

timestamp = 1700000000

# UTC (recommended approach)
dt_utc = datetime.fromtimestamp(timestamp, tz=timezone.utc)
print(dt_utc)
# 2023-11-14 22:13:20+00:00

print(dt_utc.isoformat())
# "2023-11-14T22:13:20+00:00"

# Get current UTC timestamp
import time
current_ts = int(time.time())
print(current_ts)

Convert to other timezones

from datetime import datetime, timezone
from zoneinfo import ZoneInfo  # Python 3.9+

timestamp = 1700000000

# Convert to Tokyo time
tokyo = datetime.fromtimestamp(timestamp, tz=ZoneInfo("Asia/Tokyo"))
print(tokyo)
# 2023-11-15 07:13:20+09:00

# Convert to New York time
ny = datetime.fromtimestamp(timestamp, tz=ZoneInfo("America/New_York"))
print(ny)
# 2023-11-14 17:13:20-05:00

# Convert to Shanghai time
shanghai = datetime.fromtimestamp(timestamp, tz=ZoneInfo("Asia/Shanghai"))
print(shanghai)
# 2023-11-15 06:13:20+08:00

Millisecond timestamps

from datetime import datetime, timezone

ms_timestamp = 1700000000000  # 13 digits = milliseconds

# Divide by 1000 to get seconds
dt = datetime.fromtimestamp(ms_timestamp / 1000, tz=timezone.utc)
print(dt)
# 2023-11-14 22:13:20+00:00

4. Bash/Shell: date -d @timestamp, macOS date -r

Linux and macOS have different date command syntax for converting timestamps. Here are both approaches.

Linux (GNU date)

# Linux (GNU coreutils date)
date -d @1700000000
# Tue Nov 14 22:13:20 UTC 2023

# With UTC explicitly
date -u -d @1700000000
# Tue Nov 14 22:13:20 UTC 2023

# ISO 8601 format
date -d @1700000000 --iso-8601=seconds
# 2023-11-14T22:13:20+00:00

macOS (BSD date)

# macOS (BSD date) - uses -r instead of -d @
date -r 1700000000
# Tue Nov 14 22:13:20 UTC 2023

# With UTC
date -u -r 1700000000
# Tue Nov 14 22:13:20 UTC 2023

Get current Unix timestamp

# Works on both Linux and macOS
date +%s
# 1700000000 (current timestamp in seconds)

# Milliseconds (Linux)
date +%s%N | cut -b1-13

# Milliseconds (macOS with Python)
python3 -c "import time; print(int(time.time() * 1000))"

Custom format

# Linux
date -d @1700000000 "+%Y-%m-%d %H:%M:%S"
# 2023-11-14 22:13:20

# macOS
date -r 1700000000 "+%Y-%m-%d %H:%M:%S"
# 2023-11-14 22:13:20

# Common format specifiers:
# %Y = 4-digit year    %m = month (01-12)
# %d = day (01-31)     %H = hour (00-23)
# %M = minute (00-59)  %S = second (00-59)
# %Z = timezone name   %z = timezone offset

5. SQL: MySQL, PostgreSQL, SQLite

Every major SQL database has built-in functions to convert between Unix timestamps and dates.

MySQL: FROM_UNIXTIME()

-- MySQL: Convert timestamp to datetime
SELECT FROM_UNIXTIME(1700000000);
-- '2023-11-14 22:13:20'

-- With custom format
SELECT FROM_UNIXTIME(1700000000, '%Y-%m-%d %H:%i:%s');
-- '2023-11-14 22:13:20'

-- In a query
SELECT id, name, FROM_UNIXTIME(created_at) AS created_date
FROM users
WHERE created_at > UNIX_TIMESTAMP('2023-01-01');

PostgreSQL: to_timestamp()

-- PostgreSQL: Convert timestamp to date
SELECT to_timestamp(1700000000);
-- '2023-11-14 22:13:20+00'

-- With timezone
SELECT to_timestamp(1700000000) AT TIME ZONE 'America/New_York';
-- '2023-11-14 17:13:20'

-- Format output
SELECT to_char(to_timestamp(1700000000), 'YYYY-MM-DD HH24:MI:SS');
-- '2023-11-14 22:13:20'

SQLite: datetime()

-- SQLite: Convert timestamp to datetime string
SELECT datetime(1700000000, 'unixepoch');
-- '2023-11-14 22:13:20'

-- In local time
SELECT datetime(1700000000, 'unixepoch', 'localtime');
-- '2023-11-14 17:13:20' (depends on server timezone)

-- With strftime
SELECT strftime('%Y-%m-%d %H:%M:%S', 1700000000, 'unixepoch');
-- '2023-11-14 22:13:20'

Reverse: Date to Unix timestamp

-- MySQL: Date to Unix timestamp
SELECT UNIX_TIMESTAMP('2023-11-14 22:13:20');
-- 1700000000

-- PostgreSQL: Date to Unix timestamp
SELECT EXTRACT(EPOCH FROM TIMESTAMP '2023-11-14 22:13:20');
-- 1700000000

-- SQLite: Date to Unix timestamp
SELECT strftime('%s', '2023-11-14 22:13:20');
-- '1700000000'

6. PHP: date(), Carbon

PHP has excellent built-in date/time functions and the popular Carbon library for more expressive code.

Built-in date()

<?php
$timestamp = 1700000000;

// Basic date() function
echo date('Y-m-d H:i:s', $timestamp);
// "2023-11-14 22:13:20"

// ISO 8601
echo date('c', $timestamp);
// "2023-11-14T22:13:20+00:00"

// RFC 2822 (email headers)
echo date('r', $timestamp);
// "Tue, 14 Nov 2023 22:13:20 +0000"

// Current timestamp
echo time();
// current Unix timestamp in seconds

DateTime class

<?php
$timestamp = 1700000000;

// DateTime class (more flexible)
$dt = new DateTime("@$timestamp");
$dt->setTimezone(new DateTimeZone('UTC'));
echo $dt->format('Y-m-d H:i:s T');
// "2023-11-14 22:13:20 UTC"

// Convert to other timezone
$dt->setTimezone(new DateTimeZone('Asia/Shanghai'));
echo $dt->format('Y-m-d H:i:s T');
// "2023-11-15 06:13:20 CST"

// DateTimeImmutable (thread-safe)
$dti = (new DateTimeImmutable("@$timestamp"))
    ->setTimezone(new DateTimeZone('America/New_York'));
echo $dti->format('Y-m-d H:i:s T');
// "2023-11-14 17:13:20 EST"

Carbon library (Laravel)

<?php
use Carbon\Carbon;

$timestamp = 1700000000;

// Carbon (popular in Laravel)
$date = Carbon::createFromTimestamp($timestamp);
echo $date->toDateTimeString();
// "2023-11-14 22:13:20"

echo $date->diffForHumans();
// "X months ago"

echo $date->timezone('Asia/Tokyo')->format('Y-m-d H:i:s');
// "2023-11-15 07:13:20"

// From milliseconds
$ms = Carbon::createFromTimestampMs(1700000000000);

7. Go: time.Unix()

Go's time package provides the Unix() function for clean timestamp conversion.

Basic conversion

package main

import (
    "fmt"
    "time"
)

func main() {
    timestamp := int64(1700000000)

    // Convert seconds to time.Time
    t := time.Unix(timestamp, 0)
    fmt.Println(t.UTC())
    // 2023-11-14 22:13:20 +0000 UTC

    fmt.Println(t.UTC().String())
    // "2023-11-14 22:13:20 +0000 UTC"
}

Custom formatting

package main

import (
    "fmt"
    "time"
)

func main() {
    t := time.Unix(1700000000, 0).UTC()

    // Go uses a reference time: Mon Jan 2 15:04:05 MST 2006
    fmt.Println(t.Format("2006-01-02 15:04:05"))
    // "2023-11-14 22:13:20"

    fmt.Println(t.Format(time.RFC3339))
    // "2023-11-14T22:13:20Z"

    fmt.Println(t.Format(time.RFC1123))
    // "Tue, 14 Nov 2023 22:13:20 UTC"

    // With timezone
    loc, _ := time.LoadLocation("Asia/Tokyo")
    fmt.Println(t.In(loc).Format("2006-01-02 15:04:05 MST"))
    // "2023-11-15 07:13:20 JST"

    // Get current timestamp
    now := time.Now().Unix()
    fmt.Println(now)
}

Millisecond timestamps

package main

import (
    "fmt"
    "time"
)

func main() {
    msTimestamp := int64(1700000000000) // milliseconds

    // Unix() takes (seconds, nanoseconds)
    t := time.Unix(0, msTimestamp*int64(time.Millisecond))
    fmt.Println(t.UTC())
    // 2023-11-14 22:13:20 +0000 UTC

    // Or divide by 1000
    t2 := time.Unix(msTimestamp/1000, 0)
    fmt.Println(t2.UTC())
    // 2023-11-14 22:13:20 +0000 UTC
}

8. Milliseconds vs Seconds: How to Detect and Convert

One of the most common bugs when working with timestamps is mixing up seconds and milliseconds. Here is how to tell them apart and convert between them.

  • Seconds timestamps are typically 10 digits (e.g., 1700000000) and represent dates in the 2020s range.
  • Millisecond timestamps are typically 13 digits (e.g., 1700000000000).
  • If a timestamp produces a date in the year 50000+, you probably passed milliseconds to a function expecting seconds.
  • If a timestamp produces a date in January 1970, you probably passed seconds to a function expecting milliseconds.

Quick conversion formulas

// Detect: count digits
function isMilliseconds(ts) {
  return ts.toString().length >= 13;
}

// Seconds to milliseconds
const ms = seconds * 1000;

// Milliseconds to seconds
const sec = Math.floor(milliseconds / 1000);

// Auto-detect and normalize to seconds
function toSeconds(ts) {
  return ts > 9999999999 ? Math.floor(ts / 1000) : ts;
}

// Python equivalent
def to_seconds(ts):
    return ts // 1000 if ts > 9999999999 else ts

9. Notable Unix Timestamps

Some Unix timestamps have special significance in computing history and future.

TimestampDate (UTC)Significance
01970-01-01 00:00:00Unix Epoch (the beginning)
-141829401969-07-20 20:17:40Moon landing (negative timestamp)
9466848002000-01-01 00:00:00Y2K (Year 2000)
10000000002001-09-09 01:46:40First billionth second
20000000002033-05-18 03:33:20Two billionth second
21474836472038-01-19 03:14:0732-bit overflow (Year 2038 Problem) (Max signed 32-bit int)
# Verify notable timestamps yourself:

# Bash (Linux)
date -u -d @0                # Thu Jan  1 00:00:00 UTC 1970
date -u -d @946684800        # Sat Jan  1 00:00:00 UTC 2000
date -u -d @2147483647       # Tue Jan 19 03:14:07 UTC 2038

# Python
from datetime import datetime, timezone
datetime.fromtimestamp(2147483647, tz=timezone.utc)
# datetime(2038, 1, 19, 3, 14, 7, tzinfo=timezone.utc)

# JavaScript
new Date(2147483647 * 1000).toISOString()
// "2038-01-19T03:14:07.000Z"

10. Timezone Gotchas: UTC vs Local

Timezone handling is the #1 source of timestamp-related bugs. Here are the critical rules to remember.

  • Unix timestamps are always UTC. There is no such thing as a "local" Unix timestamp.
  • When you call new Date(ts * 1000) in JavaScript, the Date object stores UTC internally but .toString() displays in the user's local timezone.
  • Python's datetime.fromtimestamp() returns local time by default. Use datetime.fromtimestamp(ts, tz=timezone.utc) for UTC.
  • Always store timestamps in UTC and convert to local time only for display.
  • Be careful with daylight saving time (DST) transitions. The same local time can occur twice (fall back) or not at all (spring forward).

JavaScript: UTC vs Local output

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

// These are DIFFERENT if you're not in UTC:
console.log(date.toString());
// "Tue Nov 14 2023 17:13:20 GMT-0500 (Eastern Standard Time)"
//  ^ Local time

console.log(date.toUTCString());
// "Tue, 14 Nov 2023 22:13:20 GMT"
//  ^ UTC time

console.log(date.toISOString());
// "2023-11-14T22:13:20.000Z"
//  ^ Always UTC (the Z means Zulu/UTC)

// Safe: always use UTC methods
console.log(date.getUTCHours());   // 22 (UTC)
console.log(date.getHours());       // 17 (local, if EST)
# Python timezone comparison
from datetime import datetime, timezone
from zoneinfo import ZoneInfo

ts = 1700000000

# WRONG: naive datetime (no timezone info)
naive = datetime.fromtimestamp(ts)
print(naive)  # ambiguous - depends on server timezone

# RIGHT: timezone-aware
utc = datetime.fromtimestamp(ts, tz=timezone.utc)
print(utc)    # 2023-11-14 22:13:20+00:00

# Convert between zones safely
eastern = utc.astimezone(ZoneInfo("America/New_York"))
print(eastern)  # 2023-11-14 17:13:20-05:00

# The underlying timestamp is always the same
print(utc.timestamp() == eastern.timestamp())  # True

Frequently Asked Questions

What is a Unix timestamp?

A Unix timestamp (also called Epoch time or POSIX time) is the number of seconds that have elapsed since January 1, 1970, 00:00:00 UTC. It is a timezone-independent way to represent a specific moment in time as a single integer.

Why does JavaScript use milliseconds instead of seconds?

JavaScript's Date object was designed to match Java's java.util.Date, which uses milliseconds for higher precision. When working with Unix timestamps in JavaScript, always multiply seconds by 1000: new Date(timestamp * 1000).

What is the Year 2038 problem?

Systems that store Unix timestamps as a signed 32-bit integer will overflow on January 19, 2038 at 03:14:07 UTC, when the value exceeds 2,147,483,647. The timestamp will wrap to a negative number, causing the date to jump back to 1901. Most modern systems now use 64-bit integers, which won't overflow for 292 billion years.

How do I get the current Unix timestamp?

JavaScript: Math.floor(Date.now() / 1000). Python: import time; int(time.time()). Bash: date +%s. PHP: time(). Go: time.Now().Unix(). All return seconds since epoch in UTC.

Can Unix timestamps be negative?

Yes. Negative Unix timestamps represent dates before January 1, 1970. For example, -1 represents December 31, 1969 at 23:59:59 UTC. The Moon landing on July 20, 1969 has the timestamp -14182940. Most modern languages and databases support negative timestamps correctly.

Try our Unix Timestamp Converter tool
𝕏 Twitterin LinkedIn
Var detta hjälpsamt?

Håll dig uppdaterad

Få veckovisa dev-tips och nya verktyg.

Ingen spam. Avsluta när som helst.

Try These Related Tools

🕐Unix Timestamp Converter⏱️Unix Timestamp ConverterCron Expression Parser

Related Articles

Cron-uttryck exempel: var 5:e minut, dagligen, veckovis

Bemästra cron-uttryck med praktiska exempel.

JavaScript datumformat: Komplett guide

Lär dig alla sätt att formatera datum i JavaScript: toLocaleDateString, Intl.DateTimeFormat, ISO och populära bibliotek.