>>> 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
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.
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.”
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.
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With