ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question
0

How to convert a timestamp from std::chrono::nanoseconds to ros::Time ?

asked 2022-08-27 12:54:04 -0600

ros_user_ak gravatar image

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

edit retag flag offensive close merge delete

Comments

ravijoshi gravatar image ravijoshi  ( 2022-08-27 21:40:10 -0600 )edit
1

@ravijoshi You should make your comment the answer.

Mike Scheutzow gravatar image Mike Scheutzow  ( 2022-08-28 07:43:44 -0600 )edit

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-08-28 08:49:46 -0600

ravijoshi gravatar image

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).

edit flag offensive delete link more

Comments

1

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.

ros_user_ak gravatar image ros_user_ak  ( 2022-08-28 13:56:34 -0600 )edit

Please read the answer properly and look at the documentation carefully.

ravijoshi gravatar image ravijoshi  ( 2022-08-28 20:37:42 -0600 )edit

Question Tools

2 followers

Stats

Asked: 2022-08-27 12:54:04 -0600

Seen: 821 times

Last updated: Aug 28 '22