Point Cloud Library (PCL)  1.14.0-dev
timestamp.h
1 /*
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Point Cloud Library (PCL) - www.pointclouds.org
5  * Copyright (c) 2023-, Open Perception
6  *
7  * All rights reserved
8  */
9 
10 #include <pcl/pcl_exports.h>
11 
12 #include <chrono>
13 #include <iomanip>
14 #include <sstream>
15 #include <string>
16 
17 namespace pcl {
18 /**
19  * @brief Returns a timestamp in local time as string formatted like boosts to_iso_string see https://www.boost.org/doc/libs/1_81_0/doc/html/date_time/posix_time.html#ptime_to_string
20  * Example: 19750101T235959.123456
21  * @param time std::chrono::timepoint to convert, defaults to now
22  * @return std::string containing the timestamp
23 */
24 PCL_EXPORTS inline std::string
25 getTimestamp(const std::chrono::time_point<std::chrono::system_clock>& time =
26  std::chrono::system_clock::now())
27 {
28  const auto us =
29  std::chrono::duration_cast<std::chrono::microseconds>(time.time_since_epoch());
30 
31  const auto s = std::chrono::duration_cast<std::chrono::seconds>(us);
32  std::time_t tt = s.count();
33  std::size_t fractional_seconds = us.count() % 1000000;
34 
35  std::tm tm = *std::localtime(&tt); // local time
36  std::stringstream ss;
37  ss << std::put_time(&tm, "%Y%m%dT%H%M%S");
38 
39  if (fractional_seconds > 0) {
40  ss << "." << std::setw(6) << std::setfill('0') << fractional_seconds;
41  }
42 
43  return ss.str();
44 }
45 
46 /**
47  * @brief Parses a iso timestring (see https://www.boost.org/doc/libs/1_81_0/doc/html/date_time/posix_time.html#ptime_to_string) and returns a timepoint
48  * @param timestamp as string formatted like boost iso date
49  * @return std::chrono::time_point with system_clock
50 */
51 PCL_EXPORTS inline std::chrono::time_point<std::chrono::system_clock>
52 parseTimestamp(std::string timestamp)
53 {
54  std::istringstream ss;
55 
56  std::tm tm = {};
57 
58  std::size_t fractional_seconds = 0;
59 
60  ss.str(timestamp);
61  ss >> std::get_time(&tm, "%Y%m%dT%H%M%S");
62 
63  auto timepoint = std::chrono::system_clock::from_time_t(std::mktime(&tm));
64 
65  const auto pos = timestamp.find('.');
66 
67  if (pos != std::string::npos) {
68  const auto frac_text = timestamp.substr(pos+1);
69  ss.str(frac_text);
70  ss >> fractional_seconds;
71  timepoint += std::chrono::microseconds(fractional_seconds);
72  }
73 
74  return timepoint;
75 }
76 
77 } // namespace pcl
PCL_EXPORTS std::chrono::time_point< std::chrono::system_clock > parseTimestamp(std::string timestamp)
Parses a iso timestring (see https://www.boost.org/doc/libs/1_81_0/doc/html/date_time/posix_time....
Definition: timestamp.h:52
PCL_EXPORTS std::string getTimestamp(const std::chrono::time_point< std::chrono::system_clock > &time=std::chrono::system_clock::now())
Returns a timestamp in local time as string formatted like boosts to_iso_string see https://www....
Definition: timestamp.h:25
#define PCL_EXPORTS
Definition: pcl_macros.h:323