Common Unix Timestamp Use Cases

Practical applications and real-world scenarios where Unix timestamps prove essential for developers and system administrators.

API Development

REST APIs

Unix timestamps are widely used in REST APIs for consistent time representation across different systems and timezones.

api-response.jsonjson
1{
2  "id": 12345,
3  "title": "Sample Post",
4  "content": "This is a sample blog post.",
5  "created_at": 1703980800,
6  "updated_at": 1703984400,
7  "published_at": 1703988000,
8  "author": {
9    "id": 67890,
10    "name": "John Doe",
11    "last_login": 1703970000
12  },
13  "comments": [
14    {
15      "id": 1,
16      "text": "Great post!",
17      "timestamp": 1703990400,
18      "author_id": 11111
19    }
20  ]
21}

API Best Practices:

  • • Use consistent field naming (created_at, updated_at)
  • • Always store timestamps in UTC
  • • Include timezone information in documentation
  • • Consider providing both Unix timestamp and ISO 8601 formats

GraphQL APIs

schema.graphqlgraphql
1type Post {
2  id: ID!
3  title: String!
4  content: String!
5  createdAt: Int!  # Unix timestamp
6  updatedAt: Int!  # Unix timestamp
7  publishedAt: Int # Optional Unix timestamp
8  author: User!
9}
10
11type Query {
12  posts(
13    after: Int     # Unix timestamp for pagination
14    before: Int    # Unix timestamp for filtering
15    limit: Int = 10
16  ): [Post!]!
17}
18
19type Mutation {
20  createPost(input: CreatePostInput!): Post!
21  schedulePost(
22    input: CreatePostInput!
23    publishAt: Int!  # Unix timestamp for scheduling
24  ): Post!
25}

Database Operations

Event Tracking

Track user events, system events, and application state changes with precise timing.

event-tracking.sqlsql
1-- Create events table
2CREATE TABLE user_events (
3    id BIGINT PRIMARY KEY AUTO_INCREMENT,
4    user_id BIGINT NOT NULL,
5    event_type VARCHAR(50) NOT NULL,
6    event_data JSON,
7    timestamp BIGINT NOT NULL,
8    session_id VARCHAR(255),
9    ip_address VARCHAR(45),
10    INDEX idx_user_timestamp (user_id, timestamp),
11    INDEX idx_event_type_timestamp (event_type, timestamp)
12);
13
14-- Insert events
15INSERT INTO user_events (user_id, event_type, event_data, timestamp, session_id)
16VALUES 
17    (12345, 'page_view', '{"page": "/dashboard", "duration": 45}', 1703980800, 'sess_abc123'),
18    (12345, 'button_click', '{"button": "export", "section": "reports"}', 1703980815, 'sess_abc123'),
19    (12345, 'logout', '{}', 1703985600, 'sess_abc123');
20
21-- Query events in time range
22SELECT event_type, COUNT(*) as count
23FROM user_events 
24WHERE timestamp BETWEEN 1703980800 AND 1704067200  -- Last 24 hours
25GROUP BY event_type
26ORDER BY count DESC;

Data Versioning

Implement audit trails and data versioning using timestamps for compliance and debugging.

audit-table.sqlsql
1-- Audit table for tracking changes
2CREATE TABLE user_audit (
3    id BIGINT PRIMARY KEY AUTO_INCREMENT,
4    user_id BIGINT NOT NULL,
5    field_name VARCHAR(50) NOT NULL,
6    old_value TEXT,
7    new_value TEXT,
8    changed_by BIGINT NOT NULL,
9    changed_at BIGINT NOT NULL,
10    change_reason VARCHAR(255),
11    INDEX idx_user_changed_at (user_id, changed_at)
12);
13
14-- Trigger to automatically audit changes
15DELIMITER //
16CREATE TRIGGER user_audit_trigger 
17AFTER UPDATE ON users
18FOR EACH ROW
19BEGIN
20    IF OLD.email != NEW.email THEN
21        INSERT INTO user_audit (user_id, field_name, old_value, new_value, changed_by, changed_at)
22        VALUES (NEW.id, 'email', OLD.email, NEW.email, NEW.updated_by, UNIX_TIMESTAMP());
23    END IF;
24END//
25DELIMITER ;

Log Analysis and Monitoring

Application Logs

Structure application logs with Unix timestamps for consistent parsing and analysis.

logger.jsjavascript
1class Logger {
2    constructor(service) {
3        this.service = service;
4    }
5
6    log(level, message, metadata = {}) {
7        const logEntry = {
8            timestamp: Math.floor(Date.now() / 1000),
9            level,
10            service: this.service,
11            message,
12            ...metadata
13        };
14        
15        console.log(JSON.stringify(logEntry));
16    }
17
18    info(message, metadata) {
19        this.log('INFO', message, metadata);
20    }
21
22    error(message, error, metadata) {
23        this.log('ERROR', message, {
24            error: {
25                name: error.name,
26                message: error.message,
27                stack: error.stack
28            },
29            ...metadata
30        });
31    }
32}
33
34// Usage
35const logger = new Logger('user-service');
36logger.info('User login successful', { 
37    userId: 12345, 
38    ip: '192.168.1.100',
39    userAgent: 'Mozilla/5.0...'
40});
41
42// Output:
43// {"timestamp":1703980800,"level":"INFO","service":"user-service","message":"User login successful","userId":12345,"ip":"192.168.1.100","userAgent":"Mozilla/5.0..."}

System Monitoring

monitoring.pypython
1import time
2import psutil
3import json
4
5def collect_system_metrics():
6    """Collect system metrics with timestamps"""
7    timestamp = int(time.time())
8    
9    metrics = {
10        'timestamp': timestamp,
11        'cpu_percent': psutil.cpu_percent(interval=1),
12        'memory': {
13            'total': psutil.virtual_memory().total,
14            'available': psutil.virtual_memory().available,
15            'percent': psutil.virtual_memory().percent
16        },
17        'disk': {
18            'total': psutil.disk_usage('/').total,
19            'used': psutil.disk_usage('/').used,
20            'free': psutil.disk_usage('/').free
21        },
22        'network': {
23            'bytes_sent': psutil.net_io_counters().bytes_sent,
24            'bytes_recv': psutil.net_io_counters().bytes_recv
25        }
26    }
27    
28    return metrics
29
30# Collect metrics every minute
31while True:
32    metrics = collect_system_metrics()
33    print(json.dumps(metrics))
34    time.sleep(60)

Caching and Expiration

Implement cache expiration and TTL (Time To Live) mechanisms using Unix timestamps.

cache.jsjavascript
1class SimpleCache {
2    constructor() {
3        this.cache = new Map();
4    }
5
6    set(key, value, ttlSeconds = 3600) {
7        const expiresAt = Math.floor(Date.now() / 1000) + ttlSeconds;
8        this.cache.set(key, {
9            value,
10            expiresAt
11        });
12    }
13
14    get(key) {
15        const item = this.cache.get(key);
16        if (!item) return null;
17
18        const now = Math.floor(Date.now() / 1000);
19        if (now > item.expiresAt) {
20            this.cache.delete(key);
21            return null;
22        }
23
24        return item.value;
25    }
26
27    cleanup() {
28        const now = Math.floor(Date.now() / 1000);
29        for (const [key, item] of this.cache.entries()) {
30            if (now > item.expiresAt) {
31                this.cache.delete(key);
32            }
33        }
34    }
35}
36
37// Usage
38const cache = new SimpleCache();
39cache.set('user:12345', { name: 'John Doe' }, 1800); // 30 minutes TTL
40
41// Clean up expired entries every 5 minutes
42setInterval(() => cache.cleanup(), 300000);

Security Applications

Use timestamps for security-related functionality like token expiration, rate limiting, and session management.

jwt-tokens.jsjavascript
1const jwt = require('jsonwebtoken');
2
3function generateToken(userId, secretKey) {
4    const now = Math.floor(Date.now() / 1000);
5    const payload = {
6        sub: userId,              // Subject (user ID)
7        iat: now,                 // Issued at
8        exp: now + (24 * 60 * 60), // Expires in 24 hours
9        jti: generateUniqueId()   // JWT ID for revocation
10    };
11    
12    return jwt.sign(payload, secretKey);
13}
14
15function verifyToken(token, secretKey) {
16    try {
17        const decoded = jwt.verify(token, secretKey);
18        const now = Math.floor(Date.now() / 1000);
19        
20        // Additional expiration check
21        if (decoded.exp < now) {
22            throw new Error('Token expired');
23        }
24        
25        return decoded;
26    } catch (error) {
27        throw new Error('Invalid token');
28    }
29}
30
31// Rate limiting example
32class RateLimiter {
33    constructor(maxRequests = 100, windowSeconds = 3600) {
34        this.maxRequests = maxRequests;
35        this.windowSeconds = windowSeconds;
36        this.requests = new Map();
37    }
38
39    isAllowed(clientId) {
40        const now = Math.floor(Date.now() / 1000);
41        const windowStart = now - this.windowSeconds;
42        
43        if (!this.requests.has(clientId)) {
44            this.requests.set(clientId, []);
45        }
46        
47        const clientRequests = this.requests.get(clientId);
48        
49        // Remove old requests outside the window
50        const validRequests = clientRequests.filter(timestamp => timestamp > windowStart);
51        this.requests.set(clientId, validRequests);
52        
53        if (validRequests.length >= this.maxRequests) {
54            return false;
55        }
56        
57        validRequests.push(now);
58        return true;
59    }
60}

Data Analysis and Reporting

Generate time-based reports and analytics using Unix timestamps for consistent data aggregation.

analytics.sqlsql
1-- Daily active users report
2SELECT 
3    DATE(FROM_UNIXTIME(login_timestamp)) as date,
4    COUNT(DISTINCT user_id) as daily_active_users
5FROM user_sessions 
6WHERE login_timestamp >= UNIX_TIMESTAMP(DATE_SUB(CURDATE(), INTERVAL 30 DAY))
7GROUP BY DATE(FROM_UNIXTIME(login_timestamp))
8ORDER BY date DESC;
9
10-- Hourly traffic analysis
11SELECT 
12    HOUR(FROM_UNIXTIME(request_timestamp)) as hour,
13    COUNT(*) as requests,
14    AVG(response_time_ms) as avg_response_time
15FROM api_logs 
16WHERE request_timestamp >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 24 HOUR))
17GROUP BY HOUR(FROM_UNIXTIME(request_timestamp))
18ORDER BY hour;
19
20-- Weekly revenue trends
21SELECT 
22    WEEK(FROM_UNIXTIME(created_at), 1) as week_number,
23    YEAR(FROM_UNIXTIME(created_at)) as year,
24    SUM(amount) as weekly_revenue,
25    COUNT(*) as transaction_count
26FROM transactions 
27WHERE created_at >= UNIX_TIMESTAMP(DATE_SUB(CURDATE(), INTERVAL 12 WEEK))
28GROUP BY year, week_number
29ORDER BY year DESC, week_number DESC;

Pro Tips for Data Analysis:

  • • Index timestamp columns for better query performance
  • • Use timestamp ranges for time-series data partitioning
  • • Consider time zone conversion at query time, not storage time
  • • Pre-aggregate data for frequently accessed time periods

Table of Contents