<!-- mobian-agent-page publisher="dailydev" canonical="https://daily.dev/posts/a-faster-way-to-convert-a-timestamp-to-hour-min-sec-5afqsbet9" -->

---
title: A faster way to convert a timestamp to Hour, Min, Sec
description: A deep dive into low-level techniques for converting a daily timestamp into hour, minute, and second, showing how most date/time libraries (Linux kernel,...
canonical: https://daily.dev/posts/a-faster-way-to-convert-a-timestamp-to-hour-min-sec-5afqsbet9
twitter:card: summary_large_image
twitter:site: @dailydotdev
og:type: website
og:site_name: daily.dev
og:title: A faster way to convert a timestamp to Hour, Min, Sec | daily.dev
og:description: A deep dive into low-level techniques for converting a daily timestamp into hour, minute, and second, showing how most date/time libraries (Linux kernel,...
og:url: https://daily.dev/posts/a-faster-way-to-convert-a-timestamp-to-hour-min-sec-5afqsbet9
og:image: https://api.daily.dev/og/posts/5AFQSbeT9.png
og:image:alt: A faster way to convert a timestamp to Hour, Min, Sec
og:image:width: 1200
og:image:height: 630
og:locale: en
---

> ## Documentation Index
> Fetch the complete documentation index at: https://daily.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# A faster way to convert a timestamp to Hour, Min, Sec

**[Lobsters](https://daily.dev/sources/lobsters)** · 22 min read · 6 upvotes · 0 comments

## Summary

A deep dive into low-level techniques for converting a daily timestamp into hour, minute, and second, showing how most date/time libraries (Linux kernel, glibc, Go, CPython, OpenJDK) use a slow dependency chain requiring ~16 cpu cycles. The piece walks through progressively faster approaches, including breaking dependency chains, using mul-shift tricks instead of division, fixed-point high/low bit extraction (building on Cassio Neri's and Lemire's techniques), and a final 'Base-64 Clock Trick' that achieves latency of only two multiplications (around 5-6 cycles). It also covers millisecond decomposition, leap-second handling, and SIMD/ARM Neon-specific variants, backed by extensive cross-platform benchmarks (Apple M4 Pro, AMD Ryzen, Raspberry Pi Zero) across compilers (Clang, GCC, MSVC).

## Full article

daily.dev links to this article rather than hosting it. Read it at the original source: <https://www.benjoffe.com/fast-time-of-day>

## Questions this post answers

### How can I convert a timestamp in the range 0 to 86399 seconds into hour, minute, and second faster than the standard division and modulo approach?

Break the dependency chain by computing total minutes and hour in parallel first, then deriving minute and second from those intermediate results rather than chaining divisions. Using fixed-point multiply-shift constants (1193047 for hours, 71582789 for minutes, both derived as (1<<32)/divisor+1) replaces division with multiplication, letting compilers emit as few as four multiplications with roughly 5-6 cycle latency instead of the ~16 cycles used by most date libraries.

_Developers benchmarking time-conversion code across platforms can track performance techniques like this on daily.dev._

### Why do most date and time libraries like glibc, the Linux kernel, and Go's standard library compute hour, minute, and second slowly?

They use a sequential dependency chain: hour is computed from time, then remainder depends on hour, minute depends on remainder, and second depends on minute. This chain, used in the Linux kernel, glibc, Go's standard library, CPython's datetime, and OpenJDK's java.time, has around 16 cpu-cycles of latency because nothing in the chain can execute in parallel on a superscalar processor.

_Anyone weighing tradeoffs between date library implementations can follow deep dives like this on daily.dev._

### What is the fastest branch-free way to handle a leap second (23:59:60) when converting a timestamp to hour, minute, second?

Detect if the timestamp equals 86400, subtract that flag before running the normal conversion, then add the flag back to the computed second field afterward, avoiding any branching. An alternative avoids even that subtraction penalty by pre-incrementing the timestamp and using adjusted fixed-point multipliers (143163919 and 2386065) so the rounding error in the math lines up exactly on the final leap second.

_Engineers implementing UTC-aware time libraries can dig into branch-free leap-second handling like this on daily.dev._

## Community take

How the wider developer community reacted, aggregated from 2 discussions and 8 comments across lobsters, hackernews (as of 2026-09-14).

**TL;DR:** Commenters found the deep-dive impressive and well-tested, sparking a broader discussion about how misleading assumptions about low-level performance (like division being 'free') can be, while also noting that ultra-optimized code trades off readability.

**Sentiment:** 65% positive · 30% mixed · 5% skeptical

**The case for**

- The explanations and benchmarks are seen as clear, thorough, and visually well-presented.
- Prompted useful tangential discussion about compilers already optimizing division/modulo by constants into multiplications.
- Appreciated the author's own caveat that the simplest, most readable version may be preferable despite being slower.

**The pushback**

- Some worry that highly optimized code becomes much harder to read and maintain, as seen when a similar optimization made a Go codebase confusing to follow.
- Raised doubts about how durable these micro-optimizations will remain as hardware and compilers evolve over time.

**By community**

- lobsters (positive): Largely appreciative discussion praising the clarity and depth of the analysis, with side conversations about compiler optimizations and long-term durability of the tricks.
- hackernews (mixed): No substantive comment content was provided to assess sentiment.

**Hottest debate:** Whether these low-level speed tricks will remain relevant as compilers and hardware evolve, versus concerns that faster code sacrifices readability and maintainability.

**Open questions**

- Will future compilers automatically fold division-then-modulo-by-constant into a single multiplication, making this optimization unnecessary?
- How durable are these performance gains likely to be as hardware and compiler tooling evolve over the coming years?

**Highlights**

> As someone more into high-level programming, I've always found it quite nebulous the performance characteristics of low-level operations such as these. Here I am thinking that division and modulo are single processor instructions and therefore the most optimal possible, and then an article like this comes along to give me a reality check. It makes me wonder how much of what I think I know about compiled code is actually true. I try to avoid unnecessary allocations for performance but then, who knows, maybe for some reason I'm unaware of, some allocations are sometimes actually more optimal because of some other subtlety. If you take this to the logical extreme, the same is true of *every* level of abstraction, from the way the compiler generates machine code all the way to how your GUI library is implemented.  No wonder software is slow.
> — [Timwi on lobsters · 4 points, 2 comments](https://lobste.rs/s/wolwwd/faster_way_convert_timestamp_hour_min_sec#c_qzdkyn)

> Thank you for sharing. This (and the [previous submission in this series](https://lobste.rs/s/ln3dao/faster_way_calculate_day_week)) have been very interesting to read. The improvements over the naïve approaches seem significant—2× better latency in the best cases. How durable are these results expected to be over time?  The improvements are fairly self-contained, so I suppose updating this article in two or five or ten years and swapping out your datetime routines is not that much of a burden, though an interesting exercise might be to apply these improvements to historical architectures using contemporaneous compiler tooling to see whether whether the best today was, in fact, always the best yesterday (and, one would try to predict, the best to-morrow.) (In general, is it not the case for µoptimisations that the “dumb, slow” way is often a more visible target for benchmark-motivated hardware designers and, thus, the advantages of the “clever, fast” approaches will necessarily decay over time? Of course, I suppose one might argue that there is something  hardware is already quite mature, yet these opportunities are still presenting themselves…)
> — [dutc on lobsters · 1 points](https://lobste.rs/s/wolwwd/faster_way_convert_timestamp_hour_min_sec#c_wcrbay)

> Reminded me of the times I've look at Go's `time.Time` implementation since I needed a version that worked with the day split into four units (so an accuracy of just night, morning, afternoon, and evening). For my initial implementation it was really easy to port the Go code to Rust and make the modifications I needed. Some time later I returned to it and needed to make some changes and the Go codebase had optimized pretty much all of the algorithms and made the code really hard to read and copy from... I spent quite a good while confused at how I had ever ported the code until I realized to look at the `git` history for the previous version. All of this to say that I appreciate your closing thoughts of >If you want clean readable math, choose "V1". instead of automatically assuming that faster is better in all cases.
> — [payne on lobsters · 1 points](https://lobste.rs/s/wolwwd/faster_way_convert_timestamp_hour_min_sec#c_ezxjlp)

> Compilers can rewrite division-by-constant or modulo-by-constant into a multiplication. What's weird is that I haven't yet seen the division-by-constant followed by the modulo-by-that-same-constant be optimized by a single multiplication, but I assume that's just a matter of time (and someone reading this comment and going "Aha!") See: https://en.wikipedia.org/wiki/Division_algorithm#Division_by_a_constant And once that work goes into an optimizing compiler, you should be able to pick up the optimization from this article mostly "for free".
> — [cpurdy on lobsters · 1 points, 1 comments](https://lobste.rs/s/wolwwd/faster_way_convert_timestamp_hour_min_sec#c_gshkkk)

**Source threads**

- [lobsters](https://lobste.rs/s/wolwwd/faster_way_convert_timestamp_hour_min_sec) · 68 points · 8 comments
- [hackernews](https://news.ycombinator.com/item?id=49596678) · 4 points · 0 comments

## Similar posts on daily.dev

- [A Very Fast 64–Bit Date Algorithm: 30-40% faster](https://daily.dev/posts/a-very-fast-64-bit-date-algorithm-30-40-faster-ujuth5oxm) · Hacker News · 1 upvotes · 0 comments
- [The fastest Linux timestamps · hmpc](https://daily.dev/posts/the-fastest-linux-timestamps-hmpc-evqoy4ob7) · Lobsters · 0 upvotes · 0 comments
- [One Giant Leap: 95% Less Sampling Cost](https://daily.dev/posts/one-giant-leap-95-less-sampling-cost-knpvkaex9) · Inside Java · 0 upvotes · 0 comments

---

Tags: [#performance](https://daily.dev/tags/performance), [#c](https://daily.dev/tags/c), [#algorithms](https://daily.dev/tags/algorithms)

[View this post on daily.dev](https://daily.dev/posts/a-faster-way-to-convert-a-timestamp-to-hour-min-sec-5afqsbet9)

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://daily.dev/#organization","name":"daily.dev","url":"https://daily.dev","logo":{"@type":"ImageObject","url":"https://daily.dev/apple-touch-icon.png","width":180,"height":180},"sameAs":["https://twitter.com/dailydotdev","https://github.com/dailydotdev","https://www.linkedin.com/company/daily-dev-ltd"]},{"@type":"WebSite","@id":"https://daily.dev/#website","url":"https://daily.dev","name":"daily.dev","publisher":{"@id":"https://daily.dev/#organization"},"potentialAction":{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https://daily.dev/search?q={search_term_string}"},"query-input":"required name=search_term_string"}}]}
{"@context":"https://schema.org","@type":"TechArticle","headline":"A faster way to convert a timestamp to Hour, Min, Sec","url":"https://daily.dev/posts/a-faster-way-to-convert-a-timestamp-to-hour-min-sec-5afqsbet9","mainEntityOfPage":{"@type":"WebPage","@id":"https://daily.dev/posts/a-faster-way-to-convert-a-timestamp-to-hour-min-sec-5afqsbet9"},"datePublished":"2026-09-07T13:56:05.712Z","dateModified":"2026-09-14T07:33:22.803Z","description":"A deep dive into low-level techniques for converting a daily timestamp into hour, minute, and second, showing how most date/time libraries (Linux kernel,...","image":"https://media.daily.dev/image/upload/f_auto,q_auto/v1/posts/d89efa5e8d3ce1023297017ef0771dc1?_a=AQAEuop","thumbnailUrl":"https://media.daily.dev/image/upload/f_auto,q_auto/v1/posts/d89efa5e8d3ce1023297017ef0771dc1?_a=AQAEuop","isAccessibleForFree":true,"articleSection":"Lobsters","inLanguage":"en","publisher":{"@type":"Organization","name":"daily.dev","url":"https://daily.dev","logo":{"@type":"ImageObject","url":"https://daily.dev/apple-touch-icon.png","width":180,"height":180}},"author":{"@type":"Organization","name":"Lobsters","logo":"https://media.daily.dev/image/upload/s--tl8v_Fku--/f_auto,t_logo/v1698841318/logos/lobste.jpg","url":"https://daily.dev/sources/lobsters"},"commentCount":0,"discussionUrl":"https://daily.dev/posts/a-faster-way-to-convert-a-timestamp-to-hour-min-sec-5afqsbet9","interactionStatistic":[{"@type":"InteractionCounter","interactionType":{"@type":"LikeAction"},"userInteractionCount":6},{"@type":"InteractionCounter","interactionType":{"@type":"CommentAction"},"userInteractionCount":0}],"keywords":"performance,c,algorithms","timeRequired":"PT22M"}
{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://daily.dev"},{"@type":"ListItem","position":2,"name":"Lobsters","item":"https://daily.dev/sources/lobsters"},{"@type":"ListItem","position":3,"name":"A faster way to convert a timestamp to Hour, Min, Sec"}]}
{"@context":"https://schema.org","@type":"FAQPage","@id":"https://daily.dev/posts/a-faster-way-to-convert-a-timestamp-to-hour-min-sec-5afqsbet9#faq","mainEntity":[{"@type":"Question","name":"How can I convert a timestamp in the range 0 to 86399 seconds into hour, minute, and second faster than the standard division and modulo approach?","acceptedAnswer":{"@type":"Answer","text":"Break the dependency chain by computing total minutes and hour in parallel first, then deriving minute and second from those intermediate results rather than chaining divisions. Using fixed-point multiply-shift constants (1193047 for hours, 71582789 for minutes, both derived as (1\u003c\u003c32)/divisor+1) replaces division with multiplication, letting compilers emit as few as four multiplications with roughly 5-6 cycle latency instead of the ~16 cycles used by most date libraries. Developers benchmarking time-conversion code across platforms can track performance techniques like this on daily.dev."}},{"@type":"Question","name":"Why do most date and time libraries like glibc, the Linux kernel, and Go's standard library compute hour, minute, and second slowly?","acceptedAnswer":{"@type":"Answer","text":"They use a sequential dependency chain: hour is computed from time, then remainder depends on hour, minute depends on remainder, and second depends on minute. This chain, used in the Linux kernel, glibc, Go's standard library, CPython's datetime, and OpenJDK's java.time, has around 16 cpu-cycles of latency because nothing in the chain can execute in parallel on a superscalar processor. Anyone weighing tradeoffs between date library implementations can follow deep dives like this on daily.dev."}},{"@type":"Question","name":"What is the fastest branch-free way to handle a leap second (23:59:60) when converting a timestamp to hour, minute, second?","acceptedAnswer":{"@type":"Answer","text":"Detect if the timestamp equals 86400, subtract that flag before running the normal conversion, then add the flag back to the computed second field afterward, avoiding any branching. An alternative avoids even that subtraction penalty by pre-incrementing the timestamp and using adjusted fixed-point multipliers (143163919 and 2386065) so the rounding error in the math lines up exactly on the final leap second. Engineers implementing UTC-aware time libraries can dig into branch-free leap-second handling like this on daily.dev."}}]}
```

