Format std::time_point in ISO 8601 format with fractional seconds / microseconds in C++

A C++ function to format an std::time_point as an ISO 8601 string.

The C++ std chrono stuff is very useful but a bit of a head-wreck!  One of the things I had problems with was how to take an std::time_point value and format it as a string with the fractional seconds / microseconds included.  This sort of time resolution is often required for accurately time stamping machine vision images, especially when acquiring at  high rates from multiple cameras – accurate timestamps allow you to compare images from different cameras that were taken at the ‘same time’.

Anyway if you’re happy to wait for C++20 then you will have access to a format() function; but if you’re more eager to format your time strings now, then here is a function which may fit the bill, it (the function) has to jump through some hoops, but gets there in the end.

Note: This function uses the std::chrono::system_clock but it could be converted (or templated) for other std clocks..