How to Convert Unix Timestamps (Epoch Time) in Any Language
Learn what Unix timestamps are and how to convert epoch time in Python, JavaScript, Java, and Excel. Includes timezone handling and our free converter tool.
If you’ve ever opened a database or API response and found a number like 1672531200 instead of a date, you’ve met the Unix Timestamp.
While convenient for computers, these “Epoch” times are unreadable to humans. This guide explains what they are and how to convert them in popular programming languages.
What is Unix Time?
Unix time is a system for describing a point in time. It’s defined as the number of seconds that have elapsed since the Unix Epoch, minus leap seconds.
- The Epoch: January 1, 1970 at 00:00:00 UTC.
- Before 1970: Represented by negative numbers.
Seconds vs. Milliseconds
Be careful! Some systems use milliseconds (13 digits) instead of seconds (10 digits).
- Seconds:
1672531200 - Milliseconds:
1672531200000
If your conversion results in a year like “54,000 AD,” you probably treated milliseconds as seconds.
How to Convert in Code
JavaScript / TypeScript
// Convert Seconds to Date
const date = new Date(1672531200 * 1000);
console.log(date.toISOString()); // "2023-01-01T00:00:00.000Z"
// Get Current Timestamp
const now = Math.floor(Date.now() / 1000);
Python
import datetime
# Convert Seconds to Date
ts = 1672531200
print(datetime.datetime.utcfromtimestamp(ts))
# Get Current Timestamp
import time
now = int(time.time())
Excel / Google Sheets
Excel dates start from 1900, not 1970.
- Formula:
=(A1 / 86400) + DATE(1970,1,1) - Then format the cell as a Date.
How to Convert in Code (Continued)
Java
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
// Convert Seconds to Date
long timestamp = 1672531200L;
Instant instant = Instant.ofEpochSecond(timestamp);
ZonedDateTime dateTime = instant.atZone(ZoneId.of("UTC"));
System.out.println(dateTime);
// Get Current Timestamp
long now = Instant.now().getEpochSecond();
PHP
// Convert Seconds to Date
$timestamp = 1672531200;
echo date('Y-m-d H:i:s', $timestamp);
// Get Current Timestamp
$now = time();
MySQL / PostgreSQL
-- Convert Seconds to Date (MySQL)
SELECT FROM_UNIXTIME(1672531200);
-- Convert Seconds to Date (PostgreSQL)
SELECT to_timestamp(1672531200);
-- Get Current Timestamp
SELECT UNIX_TIMESTAMP(); -- MySQL
SELECT extract(epoch from now()); -- PostgreSQL
Common Pitfalls
Time Zone Confusion
Unix timestamps are always UTC. When you convert them to a readable date, the result depends on your local time zone.
Example: 1672531200 is January 1, 2023 at midnight UTC. In New York (UTC-5), that’s December 31, 2022 at 7:00 PM.
Best Practice: Always store timestamps in UTC and convert to local time only when displaying to users.
Integer Overflow
In older systems (32-bit), Unix timestamps are stored as signed 32-bit integers. This creates the Year 2038 Problem:
- Maximum value:
2147483647(January 19, 2038 at 03:14:07 UTC) - After this date, the value overflows and wraps to negative (December 13, 1901)
Solution: Use 64-bit integers (supported in modern languages) or store timestamps as strings.
Leap Seconds
Unix time ignores leap seconds. When a leap second is added to UTC, Unix time “pauses” for one second, then continues counting. For most applications, this doesn’t matter. For high-precision systems (GPS, astronomy), use TAI (International Atomic Time) instead.
Milliseconds in Databases
Some databases store timestamps in milliseconds by default:
- MongoDB: Uses milliseconds
- JavaScript Date: Uses milliseconds
- Java System.currentTimeMillis(): Returns milliseconds
Always check your database schema before inserting timestamps.
Real-World Use Cases
Session Expiration
Web applications store session creation time as a Unix timestamp. When a user makes a request, the server checks:
const sessionAge = Date.now() / 1000 - sessionTimestamp;
if (sessionAge > 3600) { // 1 hour
// Session expired, log out user
}
Sorting and Indexing
Timestamps are integers, which makes them very fast to compare and sort. Databases can index them efficiently for queries like “find all orders from the last 30 days.”
API Rate Limiting
APIs use timestamps to track when a user last made a request. If too many requests happen within a time window, the API blocks further requests.
import time
last_request = 1672531200
now = int(time.time())
if now - last_request < 60: # Less than 60 seconds
print("Rate limit exceeded. Try again later.")
Log File Analysis
Server logs often use Unix timestamps for precision and language independence. Logs from different servers in different time zones can be merged and sorted accurately.
Pro Tips
Human-Readable Logging
When debugging, convert timestamps to ISO 8601 format for readability:
// Bad (hard to read)
console.log('Event at:', 1672531200);
// Good (easy to read)
console.log('Event at:', new Date(1672531200 * 1000).toISOString());
// Output: "Event at: 2023-01-01T00:00:00.000Z"
Relative Time Display
For user interfaces, show relative time instead of absolute dates:
- “5 minutes ago” (< 1 hour)
- “3 hours ago” (< 1 day)
- “Yesterday” (1 day ago)
- “Jan 15” (older than 1 day)
Libraries like moment.js or date-fns make this easy.
Database Best Practices
- Store as INTEGER: Saves space compared to DATETIME types.
- Index timestamp columns: For fast range queries.
- Use UTC: Never store local time in databases.
Defensive Parsing
Always validate timestamps before converting:
def safe_convert(ts):
if ts < 0:
raise ValueError("Negative timestamp")
if ts > 2147483647:
# Probably milliseconds
ts = ts / 1000
return datetime.utcfromtimestamp(ts)
Use the Online Converter
Don’t want to write code? Use our Free Unix Timestamp Converter.
It automatically detects seconds vs. milliseconds, handles time zones, and even shows you the relative time (e.g., “5 minutes ago”).
Frequently Asked Questions
Why does Unix time start in 1970?
Unix was developed at Bell Labs in 1969-1970. The creators chose January 1, 1970 as a convenient “zero point” close to the system’s creation date.
What happens on January 19, 2038?
On 32-bit systems, the timestamp overflows and wraps to a negative value (the “Year 2038 Problem”). Modern systems use 64-bit timestamps, which won’t overflow until the year 292 billion.
How do I handle fractional seconds?
Use milliseconds (multiply by 1000) or microseconds (multiply by 1,000,000). Many languages support high-precision timestamps.
Can Unix timestamps represent dates before 1970?
Yes, using negative numbers. For example, -86400 represents December 31, 1969.
How do I convert between time zones?
Unix timestamps are always UTC. To convert to a different time zone, use your language’s time zone library (e.g., pytz in Python, ZoneId in Java).
Related Calculators
Related Articles
- Color Theory Basics for Web Design
Master color theory for web design including the color wheel, complementary palettes, WCAG contrast requirements, and color psychology to create effective interfaces.
- How to Minify CSS for Faster Websites
Learn what CSS minification does, why it speeds up your website, what it removes from your stylesheets, and best practices for minifying CSS in production.
- Cron Job Examples for Common Tasks (Copy-Paste Ready)
Practical cron job examples with clear explanations. Copy-paste ready crontab schedules for backups, reports, cleanup, monitoring, and automation tasks.
- Common JSON Syntax Errors and How to Fix Them
Fix JSON syntax errors fast with this developer guide. Learn the top 5 JSON parsing errors, before/after examples, and debugging techniques to validate JSON instantly.
Share this article
Have suggestions for this article?