如何以2microsecond之类的字符串形式获取0:00:00.002000时间

时间:2019-01-09 10:25:37

标签: python datetime

大家好,我有一个程序,我在该程序中完成该代码的操作所需的总时间为:

from datetime import datetime
startTime = datetime.now()
.........................
.........................
print("Total Time Taken to uploading file- " + format(datetime.now() - startTime))

输出:0:00:00.002000或0:00:20.912000 我如何将小数转换为2微秒或将其打印为20秒912微秒...在python中是否定义了任何模块?请帮助

1 个答案:

答案 0 :(得分:1)

datetime.now() - startTime返回一个timedelta object

该对象公开了total_seconds()方法,该方法输出float

因此,您应该能够将此增量转换为微秒,例如:

from datetime import datetime
import time

startTime = datetime.now()
time.sleep(0.01)

seconds = (datetime.now() - startTime).total_seconds()
print(seconds)
micro = seconds * 1000
print(micro)

输出:

0.010115 # seconds
10.115   # micro seconds