How to convert a timestamp from std::chrono::nanoseconds to ros::Time ?
How to convert a timestamp which is in std::chrono::nanoseconds to the timestamp in ros::Time ?
I tried the code as shown below:
odometry.header.stamp.fromNSec(msg.timestamp.tryToChrono())
tryToChrono() method returns std::chrono::nanoseconds
Asked by ros_user_ak on 2022-08-27 12:54:04 UTC
Answers
The ros::Time
object is made from seconds and nanoseconds, as mentioned here. Therefore, we need to extract these values (sec and nsec) from std::chrono
. See an example below:
const auto p0 = std::chrono::time_point<std::chrono::high_resolution_clock>{};
const auto p3 = std::chrono::high_resolution_clock::now();
auto tstamp = p3 - p0;
int32_t sec = std::chrono::duration_cast<std::chrono::seconds>(tstamp).count();
int32_t nsec = std::chrono::duration_cast<std::chrono::nanoseconds>(tstamp).count() % 1000000000UL;
std::cout << "sec: " << sec << " nsec: " << nsec << " since epoch: \n";
ros::Time n(sec, nsec);
Please note that the above code is taken from here.
Furthermore, you can see the API that ros::Time
can be made seconds only. Here seconds are represented by a double
datatype. Please see here and here also for more info. In short, you just need to convert nanoseconds i.e., std::chrono::nanoseconds
to seconds and use it as ros::Time n(sec)
.
Asked by ravijoshi on 2022-08-28 08:49:46 UTC
Comments
API page definition is as follows:
ros::Time::Time(uint32_t _sec, uint32_t _nsec)
Now, how would this work in the example you mentioned.
int32_t sec = std::chrono::duration_cast<std::chrono::seconds>(tstamp).count();
int32_t nsec = std::chrono::duration_cast<std::chrono::nanoseconds>(tstamp).count() % 1000000000UL;
Here both sec and nsec are int32_t.
Asked by ros_user_ak on 2022-08-28 13:56:34 UTC
Please read the answer properly and look at the documentation carefully.
Asked by ravijoshi on 2022-08-28 20:37:42 UTC
Comments
This may help.
Asked by ravijoshi on 2022-08-27 21:40:10 UTC
@ravijoshi You should make your comment the answer.
Asked by Mike Scheutzow on 2022-08-28 07:43:44 UTC