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

rospy.Time.now() sometimes returns 0.

asked 2021-10-14 05:42:46 -0600

Roshan gravatar image

updated 2021-10-14 11:38:12 -0600

Mike Scheutzow gravatar image

Hello, I'm trying to run this code:

  prevTime = rospy.Time.now()
    while not rospy.is_shutdown():
            currentTime = rospy.Time.now()

            delT = currentTime-prevTime

            print("Previous time:",prevTime.to_sec())
            print("Current time",currentTime.to_sec())
            print("Time:",delT.to_sec())

            rate.sleep()

to get the time of the while loop, because I have a function of time that needs it. Sometimes when running this, prevTime becomes 0:

Previous time: 0.0
Current time 1266.097
Time: 1266.097
Previous time: 0.0
Current time 1266.107
Time: 1266.107
Previous time: 0.0
Current time 1266.117
Time: 1266.117
Previous time: 0.0
Current time 1266.127
Time: 1266.127

And other times it works as intended:

Previous time: 1263.221
Current time 1263.321
Time: 0.1
Previous time: 1263.221
Current time 1263.331
Time: 0.11
Previous time: 1263.221
Current time 1263.341
Time: 0.12
Previous time: 1263.221
Current time 1263.351
Time: 0.13

Wondering what the issue could be, and how to stop it from becoming 0

edit retag flag offensive close merge delete

Comments

Are you using simulated time?

tryan gravatar image tryan  ( 2021-10-14 08:29:00 -0600 )edit

Yes, running the simluations in Gazebo

Roshan gravatar image Roshan  ( 2021-10-14 08:34:51 -0600 )edit

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-10-14 08:53:37 -0600

tryan gravatar image

prevTime may sometimes initialize before the first /clock message, so it defaults to 0. If you use a non-deterministic method of starting nodes, e.g., roslaunch, the startup order can vary, so this will happen sometimes but not others. As noted in the rospy Time overview, one workaround is to loop the assignment until it returns a non-zero value:

prevTime = 0
while not prevTime:
    prevTime = rospy.Time.now()
edit flag offensive delete link more

Question Tools

2 followers

Stats

Asked: 2021-10-14 05:42:46 -0600

Seen: 473 times

Last updated: Oct 14 '21