Date & Time

What is Unix Timestamp (Epoch Time)?

Learn about Unix timestamps - the number of seconds since January 1, 1970, and why it's the standard for representing time in programming.

6 min read
#unix-timestamp#epoch-time#datetime#programming#time-zone

What is a Unix Timestamp?

A Unix timestamp (also known as Epoch time or POSIX time) is a system for tracking time as a single number representing the number of seconds that have elapsed since 00:00:00 UTC on January 1, 1970 (the Unix Epoch). This simple representation makes it easy to store, compare, and calculate time differences across different time zones and systems.

Understanding the Unix Epoch

The Unix Epoch is the starting point (zero) for Unix timestamps.

Why January 1, 1970?

This date was chosen because Unix systems were being developed in the late 1960s and early 1970s. January 1, 1970 was simply a convenient, recent date that wouldn't require handling negative numbers for current dates.

text
Unix Epoch: January 1, 1970, 00:00:00 UTC

Timestamp: 0
Date: 1970-01-01 00:00:00 UTC

Timestamp: 1700000000
Date: 2023-11-14 22:13:20 UTC

Timestamp: 1731945600
Date: 2024-11-18 16:00:00 UTC

How It Works

Unix time counts forward from the epoch for dates after 1970 and backward (negative) for dates before 1970.

text
// Positive timestamps (after epoch)
1000000000  = September 9, 2001
1500000000  = July 14, 2017
2000000000  = May 18, 2033

// Negative timestamps (before epoch)
-86400      = December 31, 1969
-31536000   = January 1, 1969
-946684800  = January 1, 1940

Precision Variants

While standard Unix time uses seconds, variations exist for greater precision.

text
Unix Time (seconds):       1700000000
Unix Time (milliseconds):  1700000000000
Unix Time (microseconds):  1700000000000000
Unix Time (nanoseconds):   1700000000000000000

Common uses:
- Seconds: Unix systems, databases
- Milliseconds: JavaScript, Java
- Microseconds: Python time.time()
- Nanoseconds: High-precision timing

Working with Unix Timestamps

Examples of converting between Unix timestamps and human-readable dates:

JavaScript

JavaScript uses milliseconds since epoch, so divide/multiply by 1000 for Unix seconds.

javascript
// Get current Unix timestamp (in seconds)
const timestamp = Math.floor(Date.now() / 1000);
console.log(timestamp); // 1700000000

// Convert timestamp to Date
const date = new Date(1700000000 * 1000);
console.log(date.toISOString()); // 2023-11-14T22:13:20.000Z

// Convert Date to timestamp
const now = new Date();
const unixTime = Math.floor(now.getTime() / 1000);

// Parse specific date to timestamp
const specificDate = new Date('2024-01-01T00:00:00Z');
const specificTimestamp = Math.floor(specificDate.getTime() / 1000);

Python

Python's time and datetime modules provide Unix timestamp support.

python
import time
from datetime import datetime

# Get current Unix timestamp
timestamp = int(time.time())
print(timestamp)  # 1700000000

# Convert timestamp to datetime
dt = datetime.fromtimestamp(1700000000)
print(dt)  # 2023-11-14 22:13:20

# Convert datetime to timestamp
now = datetime.now()
timestamp = int(now.timestamp())

# UTC time
utc_dt = datetime.utcfromtimestamp(1700000000)
print(utc_dt)  # 2023-11-14 22:13:20

PHP

PHP provides built-in functions for timestamp operations.

php
<?php
// Get current Unix timestamp
$timestamp = time();
echo $timestamp; // 1700000000

// Convert timestamp to formatted date
$date = date('Y-m-d H:i:s', 1700000000);
echo $date; // 2023-11-14 22:13:20

// Convert date string to timestamp
$timestamp = strtotime('2024-01-01 00:00:00');
echo $timestamp;

// Using DateTime
$dt = new DateTime('@1700000000');
echo $dt->format('Y-m-d H:i:s');
?>

SQL Databases

Different databases have different functions for Unix timestamps.

sql
-- MySQL/MariaDB
SELECT UNIX_TIMESTAMP();  -- Current timestamp
SELECT FROM_UNIXTIME(1700000000);  -- To datetime
SELECT UNIX_TIMESTAMP('2024-01-01 00:00:00');  -- To timestamp

-- PostgreSQL
SELECT EXTRACT(EPOCH FROM NOW());  -- Current timestamp
SELECT to_timestamp(1700000000);  -- To timestamp

-- SQLite
SELECT strftime('%s', 'now');  -- Current timestamp
SELECT datetime(1700000000, 'unixepoch');  -- To datetime

Common Use Cases

Unix timestamps are widely used across different programming scenarios:

  • Database Storage: Store dates/times in a timezone-independent format
  • API Responses: Transmit datetime information between systems
  • Logging: Record when events occurred in log files
  • Caching: Set expiration times for cached data
  • Session Management: Track session creation and expiration
  • File Metadata: Store file creation and modification times
  • Scheduling: Calculate time differences and schedule tasks
  • Sorting: Easy chronological sorting of records

Advantages of Unix Timestamps

  • Simple Storage: Single integer value, efficient to store
  • Timezone Independent: Represents absolute time (UTC), avoiding timezone confusion
  • Easy Comparison: Simple numeric comparison to determine which time is earlier/later
  • Math Operations: Easy to add/subtract time intervals (just add/subtract seconds)
  • Universal: Supported by all major programming languages and databases
  • Compact: Smaller than string datetime representations
  • Sortable: Natural numeric ordering matches chronological ordering
  • No Ambiguity: No confusion about date formats (MM/DD vs DD/MM)

The Year 2038 Problem

A limitation of 32-bit Unix timestamps that developers should be aware of:

What is the Y2K38 Problem?

32-bit signed integers can only represent timestamps up to 2,147,483,647 seconds after the epoch.

text
Maximum 32-bit timestamp: 2,147,483,647
Date: Tuesday, January 19, 2038, 03:14:07 UTC

Next second (overflow):
Timestamp: 2,147,483,648
Will wrap to: -2,147,483,648
Date: Friday, December 13, 1901

This affects:
- 32-bit systems
- Legacy databases
- Embedded systems
- Old programming languages

Solutions

Modern systems use 64-bit integers to avoid this problem.

text
64-bit timestamp range:
Minimum: -9,223,372,036,854,775,808
Maximum: 9,223,372,036,854,775,807

Maximum date (far future):
Approximately year 292,277,026,596

Solutions:
- Upgrade to 64-bit systems
- Use 64-bit timestamp fields in databases
- Modern languages default to 64-bit
- Update legacy code before 2038

Handling Time Zones

Unix timestamps are UTC-based, but display requires timezone conversion:

Storage vs Display

Best practice: Store in UTC (Unix timestamp), display in user's timezone.

text
// Timestamp (UTC): 1700000000
// This represents: 2023-11-14 22:13:20 UTC

// Display in different timezones:
UTC:        2023-11-14 22:13:20
EST (UTC-5): 2023-11-14 17:13:20
PST (UTC-8): 2023-11-14 14:13:20
GMT+8:      2023-11-15 06:13:20
IST (UTC+5:30): 2023-11-15 03:43:20

Best practice:
1. Store timestamp (UTC)
2. Convert to user's timezone for display
3. Convert back to UTC for storage

Common Operations

Useful calculations with Unix timestamps:

Time Arithmetic

Easy calculations using seconds.

javascript
// Add 1 day (86400 seconds)
const tomorrow = timestamp + 86400;

// Add 1 hour (3600 seconds)
const nextHour = timestamp + 3600;

// Add 1 week (604800 seconds)
const nextWeek = timestamp + 604800;

// Calculate difference (in seconds)
const diff = timestamp2 - timestamp1;
const days = diff / 86400;
const hours = diff / 3600;

// Common time intervals:
1 minute  = 60 seconds
1 hour    = 3,600 seconds
1 day     = 86,400 seconds
1 week    = 604,800 seconds
30 days   = 2,592,000 seconds
365 days  = 31,536,000 seconds

Checking Expiration

Common pattern for checking if something has expired.

javascript
// JavaScript example
const expirationTime = 1700000000;
const currentTime = Math.floor(Date.now() / 1000);

if (currentTime > expirationTime) {
  console.log('Expired');
} else {
  const remaining = expirationTime - currentTime;
  console.log(`${remaining} seconds remaining`);
}

// Cache expiration
const cacheTime = 300; // 5 minutes
const cachedAt = 1700000000;
const isExpired = (Date.now() / 1000) > (cachedAt + cacheTime);

Best Practices

  • Always store in UTC: Use Unix timestamps or UTC datetime in databases
  • Convert for display: Only convert to local timezone when displaying to users
  • Use 64-bit timestamps: Avoid Y2K38 problem on modern systems
  • Be consistent: Use either seconds or milliseconds throughout your application
  • Validate inputs: Check timestamp ranges are reasonable
  • Use libraries: Leverage datetime libraries (moment.js, date-fns, dayjs) for complex operations
  • Document precision: Clearly specify if using seconds, milliseconds, or other precision
  • Handle leap seconds: Be aware that some systems handle leap seconds differently

Common Pitfalls

  • Seconds vs Milliseconds: JavaScript uses milliseconds, most others use seconds
  • Timezone confusion: Displaying timestamps without timezone conversion
  • 32-bit overflow: Using 32-bit integers on systems that need to work past 2038
  • Precision loss: Floating point precision issues with very large timestamps
  • Leap seconds: Not all systems handle leap seconds the same way
  • Daylight Saving Time: Let libraries handle DST conversions
  • String comparison: Comparing timestamps as strings instead of numbers

Conclusion

Unix timestamps provide a simple, universal way to represent time in computer systems. By understanding how they work, their advantages and limitations, and best practices for handling them, you can effectively manage datetime information in your applications. Remember to always store times in UTC and convert to local timezones only for display purposes.