Search code examples
c++rosunix-timestamp

How to convert `ros::Time` to string while keeping the UNIX format?


Context: I have image files with UNIX timestamps as their names, e.g. 1341846314.694004.png. The names correspond to the message header.stamp of the ROS .bag-file that publishes the images. Using Python I generated bounding box files for each image and used the same pattern to name them, e.g. 1341846314.694004_bb.txt.

Problem: I am unable to convert the header.stamp, that is of type ros::Time and of format UNIX time, to string in C++.

Every resource that I read so far, tells me to either use header.stamp.toSec() (which does not help as relevant information is being lost), or to convert it to some other time format from which I then, in turn, would be able to convert to string (which again does not help as I need the UNIX format).


Solution

  • The time classes provides fields for secs and nsecs both in Python and C++. So you can use them and combine them to a string:

    Python:

    stamp = rospy.Time.now()
    print(str(stamp.secs) + '.' + str(stamp.nsecs))
    

    C++:

    ros::Time stamp = ros::Time::now();
    std::stringstream ss;
    ss << stamp.sec << "." << stamp.nsec;
    std::cout << ss.str() << std::endl;
    

    The output for both implementations is like:

    1612707880.149451971