struct timeval to Timestamp Converter

Convert Linux/C struct timeval (tv_sec and tv_usec) to ISO 8601, Unix microsecond timestamps, pcap header dates, and timespec.

Quick Presets:

Timestamp Conversion Output

Y2038 Safe (Compatible with 32-bit & 64-bit time_t)
Calendar & Human-Readable Time
ISO 8601 (UTC)
2024-03-23T22:56:07.890123Z
  • Local Time (with Timezone Offset)2024-03-24T06:56:07.890123+08:00
Machine Timestamps & Low-Level Types
  • Unix Seconds (Floating)
    1711234567.890123
    s
  • Unix Milliseconds
    1711234567890
    ms
  • Unix Microseconds (Full Precision)
    1711234567890123
    µs
  • Equivalent struct timespec
    { tv_sec: 1711234567, tv_nsec: 890123000 }
    timespec

Cross-Language Conversion Code

Ready-to-copy code snippets for POSIX C/C++, Python, Go, and Rust:

// Convert struct timeval to ISO 8601 String in C/POSIX
#include <stdio.h>
#include <sys/time.h>
#include <time.h>

void print_timeval_iso8601(const struct timeval *tv) {
    char buf[64];
    struct tm tm_info;
    gmtime_r(&tv->tv_sec, &tm_info); // or localtime_r for local time

    // Format date-time up to seconds
    size_t len = strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S", &tm_info);
    // Append fractional microseconds and UTC 'Z'
    snprintf(buf + len, sizeof(buf) - len, ".%06ldZ", (long)tv->tv_usec);

    printf("ISO 8601: %s\n", buf);
}

int main() {
    struct timeval tv = { .tv_sec = 1711234567, .tv_usec = 890123 };
    print_timeval_iso8601(&tv);
    return 0;
}
0.0/ 5
0 ratings
Rate this tool
Click stars to rate

Comments

U

Decoding POSIX Time Structures and Timestamp Conversion

Low-level systems programming in C, C++, and Linux relies on dedicated data structures to track time with microsecond and nanosecond precision. Among these, the struct timeval structure historically anchored the POSIX gettimeofday() system call and remains universally embedded across network protocol drivers, socket timeout options (SO_RCVTIMEO, SO_SNDTIMEO), and raw packet capture files (.pcap).

A struct timeval consists of two distinct fields:

  1. tv_sec: An integer representing the number of elapsed whole seconds since the Unix Epoch (January 1, 1970, 00:00:00 UTC).
  2. tv_usec: A signed integer representing the fractional sub-second component expressed in microseconds (10−610^{-6} seconds).

While computers manipulate these two discrete fields with extreme efficiency, raw integer pairs such as { tv_sec: 1711234567, tv_usec: 890123 } are unreadable in human logs. Converting a timeval into standardized formats—such as ISO 8601 strings, Unix epoch milliseconds, or microsecond timestamps—bridges the divide between low-level kernel abstractions and high-level analytical tooling.

Architectural Comparison: Time Representation Structures in POSIX and Linux

Different system APIs, network layers, and programming environments employ distinct time structures. Choosing the correct representation prevents precision loss and data misinterpretation.

Data Structure / FormatPrecision GranularitySub-Second RepresentationTypical Header File / StandardPrimary Use Case
struct timevalMicroseconds (1 μs=10−6 s1\,\mu\text{s} = 10^{-6}\,\text{s})tv_usec (0≤μs≤999,9990 \le \mu\text{s} \le 999{,}999)<sys/time.h>gettimeofday(), socket timeouts, PCAP packet headers
struct timespecNanoseconds (1 ns=10−9 s1\,\text{ns} = 10^{-9}\,\text{s})tv_nsec (0≤ns≤999,999,9990 \le \text{ns} \le 999{,}999{,}999)<time.h>Modern POSIX clock_gettime(), nanosleep()
time_tWhole Seconds (1 s1\,\text{s})None<time.h>Standard calendar time (time(), mktime())
Unix Microsecond TimestampMicrosecondsSingle 64-bit integerDistributed systemsHigh-throughput event streaming, Kafka, Cassandra
ISO 8601 UTCMicrosecondsFormatted decimal stringISO/IEC 8601-1:2019Human-readable log files, REST APIs, JSON data

Critical Engineering Pitfalls in timeval Conversion

Converting between structured seconds-plus-microseconds and flat timestamps involves subtle edge cases that frequently produce silent errors in production telemetry.

1. The Missing Sub-Second Formatting in strftime()

A common beginner mistake in C programming is attempting to format a struct timeval directly with the standard library function strftime(). Because strftime() accepts a struct tm pointer, it only has access to whole-second fields (tm_sec, tm_min, tm_hour). Any fractional microseconds stored in tv_usec are completely omitted.

To create a valid ISO 8601 string, you must first format the calendar date and time up to the seconds field, and then append the fractional microseconds using snprintf() with an explicit zero-padding width of six digits (.%06ld).

2. Microsecond Normalization and Overflow

While POSIX specifications state that tv_usec should remain between 0 and 999,999, manual arithmetic operations—such as calculating elapsed execution duration—can easily produce unnormalized values. For instance, subtracting two timestamps without borrowing logic can yield negative microseconds, while summing timers can generate microsecond counts exceeding one million.

Unnormalized structures will fail sanity assertions in drivers and socket configuration calls. Standard POSIX macros such as timeradd automatically perform normalization by carrying excess microseconds into tv_sec.

3. The Year 2038 Problem (Y2038) and 32-Bit time_t

The Year 2038 Problem arises because 32-bit Unix systems defined tv_sec as a signed 32-bit integer (int32_t). The maximum positive value this counter can hold is 231−1=2,147,483,6472^{31} - 1 = 2{,}147{,}483{,}647. On January 19, 2038, at 03:14:07 UTC, a 32-bit signed counter will overflow into negative values, wrapping back to December 13, 1901. Modern 64-bit operating systems define time_t as a signed 64-bit integer, expanding the temporal ceiling past 292 billion years into the future.

4. PCAP Packet Header Endianness

In packet capture analysis, network packets written by tools using libpcap contain a 16-byte packet header (pcap_pkthdr). The first 8 bytes represent tv_sec and tv_usec as two 32-bit unsigned integers. Because PCAP files store headers in the native byte order of the capturing host, packets captured on x86 or ARM architectures use Little-Endian encoding, whereas captures from network switches may use Big-Endian (Network Byte Order). Decoding the hexadecimal bytes without verifying endianness will produce completely scrambled dates.

Step-by-Step Implementation in C, Python, and Go

Here is how to reliably convert struct timeval values across three mainstream engineering ecosystems.

Implementation A: Modern C/POSIX with Safe String Formatting

c
#include <stdio.h>
#include <sys/time.h>
#include <time.h>

void format_timeval_iso8601(const struct timeval *tv, char *out_buf, size_t buf_size) {
    struct tm tm_buf;
    // Thread-safe conversion to UTC calendar time
    gmtime_r(&tv->tv_sec, &tm_buf);

    // Format YYYY-MM-DDTHH:MM:SS
    size_t written = strftime(out_buf, buf_size, "%Y-%m-%dT%H:%M:%S", &tm_buf);
    if (written == 0 || written >= buf_size) return;

    // Append .uuuuuuZ
    snprintf(out_buf + written, buf_size - written, ".%06ldZ", (long)tv->tv_usec);
}

Implementation B: Python with Timezone Awareness

python
from datetime import datetime, timezone

def timeval_to_timestamp(tv_sec: int, tv_usec: int):
    # Normalize unnormalized microseconds
    carry, norm_usec = divmod(tv_usec, 1_000_000)
    norm_sec = tv_sec + carry
    
    # Construct timezone-aware UTC datetime
    dt = datetime.fromtimestamp(norm_sec, tz=timezone.utc).replace(microsecond=norm_usec)
    
    return {
        "iso_8601": dt.isoformat(),
        "epoch_microseconds": norm_sec * 1_000_000 + norm_usec,
        "epoch_milliseconds": norm_sec * 1_000 + norm_usec // 1_000
    }

Implementation C: Go Standard Library

go
package main

import (
	"fmt"
	"time"
)

func TimevalToTime(tvSec int64, tvUsec int64) (time.Time, int64) {
	// 1 microsecond = 1,000 nanoseconds
	t := time.Unix(tvSec, tvUsec*1000).UTC()
	epochMicros := tvSec*1000000 + tvUsec
	return t, epochMicros
}

Real-World Walkthrough: Extracting Microsecond Timestamps from a PCAP Hex Header

Suppose you are inspecting a raw hexadecimal packet dump from Wireshark. The packet header reveals the following initial 8 bytes of capture metadata:

65 FF 3A 67 00 05 A1 0C

To decode this byte stream into an intelligible capture timestamp:

  1. Extract 4-Byte Chunks:
    • ts_sec (Bytes 0–3): 65 FF 3A 67
    • ts_usec (Bytes 4–7): 00 05 A1 0C
  2. Reverse Little-Endian Order:
    • On an x86 capture machine, the least significant byte appears first.
    • ts_sec becomes 0x673AFF65, which converts to decimal 1,731,854,181 seconds.
    • ts_usec becomes 0x0CA10500, which converts to decimal 211,887,360 microseconds.
  3. Normalize Excess Microseconds:
    • Notice that 211,887,360 exceeds one million (211.887360211.887360 seconds).
    • Divide by 1,000,0001{,}000{,}000: Integer carry is 211211, remainder is 887,360887{,}360 microseconds.
    • Adjusted tv_sec: 1,731,854,181+211=1,731,854,3921{,}731{,}854{,}181 + 211 = 1{,}731{,}854{,}392.
  4. Final Timestamp Computation:
    • Target Date (UTC): 2024-11-17T14:39:52.887360Z.
    • Epoch Microseconds: 1731854392887360.

[Advanced Technical Insights] POSIX Microsecond Normalization and Y2038 Arithmetic

The mathematical foundation of timeval normalization guarantees that any arbitrary integer pair (sraw,uraw)∈Z2(s_{\text{raw}}, u_{\text{raw}}) \in \mathbb{Z}^2 is uniquely mapped to a canonical pair (snorm,unorm)(s_{\text{norm}}, u_{\text{norm}}) such that the fractional term satisfies 0≤unorm<1060 \le u_{\text{norm}} < 10^6.

The formal transformation is expressed using floor division and modulo arithmetic:

k=⌊uraw106⌋k = \left\lfloor \frac{u_{\text{raw}}}{10^6} \right\rfloor snorm=sraw+ks_{\text{norm}} = s_{\text{raw}} + k unorm=uraw−k×106u_{\text{norm}} = u_{\text{raw}} - k \times 10^6

To convert normalized components into a total floating-point duration TT in seconds:

T=snorm+unorm×10−6T = s_{\text{norm}} + u_{\text{norm}} \times 10^{-6}

For interconversion to nanosecond structures (struct timespec), the nanosecond component is derived strictly without floating-point loss:

ts.tv_sec=snormts.tv\_sec = s_{\text{norm}} ts.tv_nsec=unorm×103ts.tv\_nsec = u_{\text{norm}} \times 10^3

In 32-bit systems, the upper temporal bound for snorms_{\text{norm}} is determined by signed two's-complement arithmetic:

Tmax=231−1=2,147,483,647  ⟹  2038-01-19T03:14:07ZT_{\text{max}} = 2^{31} - 1 = 2{,}147{,}483{,}647 \implies \text{2038-01-19T03:14:07Z}

Any timestamp exceeding TmaxT_{\text{max}} requires signed 64-bit integers (int64_t), which provide continuous temporal representation up to:

Tmax64=263−1≈9.22×1018 secondsT_{\text{max64}} = 2^{63} - 1 \approx 9.22 \times 10^{18} \text{ seconds}

This mathematical guarantee eliminates overflow vulnerabilities across modern real-time operating systems and network infrastructure.

Frequently Asked Questions (FAQ)