Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time difference in seconds (as a floating point)

>>> from datetime import datetime >>> t1 = datetime.now() >>> t2 = datetime.now() >>> delta = t2 - t1 >>> delta.seconds 7 >>> delta.microseconds 631000 

Is there any way to get that as 7.631000 ? I can use time module, but I also need that t1 and t2 variables as DateTime objects. So if there is an easy way to do it with datettime, that would be great. Otherwise it'll look ugly:

t1 = datetime.now() _t1 = time.time() t2 = datetime.now() diff = time.time() - _t1 
like image 514
pocoa Avatar asked May 21 '10 08:05

pocoa


People also ask

How do I calculate time difference between seconds in Python?

To calculate the total time difference in seconds, use the total_seconds() method on the timedelta object time_diff . tsecs = time_diff. total_seconds() print(f"Your birthday is {tsecs} seconds away.") # Output Your birthday is 19017960.127416 seconds away.

Is Python time time in seconds?

time() Python Function The Python time() function retrieves the current time. The time is represented as the number of seconds since January 1, 1970. This is the point at which UNIX time starts, also called the “epoch.”

How do I print time in seconds in Python?

Use the time. time() function to get the current time in seconds since the epoch as a floating-point number. This method returns the current timestamp in a floating-point number that represents the number of seconds since Jan 1, 1970, 00:00:00. It returns the current time in seconds.


1 Answers

for newer version of Python (Python 2.7+ or Python 3+), you can also use the method total_seconds:

from datetime import datetime t1 = datetime.now() t2 = datetime.now() delta = t2 - t1 print(delta.total_seconds()) 
like image 164
daniel kullmann Avatar answered Sep 21 '22 17:09

daniel kullmann