2

I would like to create filenames with timestamps in them based on when the program was run, i.e.

logfile_2020-04-21_18:11:10.txt
logfile_2020-04-22_18:13:43.txt
...

I can get the timestamp (I think) with

std::chrono::steady_clock::time_point timestamp = std::chrono::steady_clock::now();

but I don't know how to convert that into a string, much less a human-readable string.

The exact format of the timestamps doesn't matter, as long as it has the full date and time. Is there a simple way to do this in C++ using standard libraries?

MountainDrew
  • 443
  • 4
  • 20
  • There's some examples [on this question](https://stackoverflow.com/questions/17223096/outputting-date-and-time-in-c-using-stdchrono): they just use `std::localtime` (or possibly `std::gmtime` for a timestamp?) and then strptime or std::put_time. – Rup May 06 '20 at 22:35
  • Possible duplicate of https://stackoverflow.com/questions/31281293/timestamps-for-embedded-system – Galik May 07 '20 at 00:20

1 Answers1

2

What you're asking for is not defined. Your timestamp is coming from a "steady" clock which guarantees monotonic time but is not related to wall clock time and thus cannot be converted into a human-readable timestamp (think about what happens if you adjust your system time -1 min, a monotonic clock can never be adjusted like this!). Monotonic clocks often count from system start. If you want to print timestamps you most likely want to use std::chrono::system_clock - for example like so:

#include <iostream>
#include <chrono>
#include <iomanip>

int main() {
  auto timestamp = std::chrono::system_clock::now();

  std::time_t now_tt = std::chrono::system_clock::to_time_t(timestamp);
  std::tm tm = *std::localtime(&now_tt);

  std::cout << std::put_time(&tm, "%c %Z") << '\n';
  return 0;
}

You can find more information on formatting the date/time in the std::put_time() documentation.

Warning: std::localtime may not be thread safe! Check the documentation of your standard library if you intend to use it in a multi-threaded context. Sometimes a reentrant version is provided as well (often called localtime_r).

Martin Konrad
  • 1,075
  • 1
  • 10
  • 20
  • Perfect, and thank you for the link to put_time(). The format I was looking for is std::put_time(&tm, "%Y-%m-%d_%H:%M:%S"). – MountainDrew May 07 '20 at 02:50