AI智能
改变未来

python 获取毫秒级时间问题的解决

根据网上的一些说法,

在python里获取ms级系统时间可以通过以下方式获取:

import datetimeprint(datetime.datetime.now().microsecond)

但通过以下代码测试,发现返回的并不是ms的值,而是us的值:

import datetimedef getTime_ms():return (datetime.datetime.now().hour*3600 +\\datetime.datetime.now().minute*60+\\datetime.datetime.now().second )*1000+\\datetime.datetime.now().microsecond/1000def timetime():t = getTime_ms()while getTime_ms() - t < 500:passa = getTime_ms()print(t, a, a- t)if __name__ == \'__main__\':from timeit import timeitt = timeit(\'timetime()\', \'from __main__ import timetime\', number=1)print(t)

打印结果

(35460614, 35461114, 500) 0.499531984329

上面实验不太直观,换一个直观点的:

def timetime():t1 = datetime.datetime.now()while 1:t2 = datetime.datetime.now()if (t2 - t1).microseconds >= 1:print(t2,t2.microsecond,t1,t1.microsecond,(t2-t1).seconds)breakif __name__ == \'__main__\':from timeit import timeitt = timeit(\'timetime()\', \'from __main__ import timetime\', number=1)print(t)#print (datetime.datetime.now())

输出

(datetime.datetime(2019, 4, 3, 10, 6, 20, 461882), 461882, datetime.datetime(2019, 4, 3, 10, 6, 20, 461863), 461863, 0) 7.10487365723e-05

def timetime():t1 = datetime.datetime.now()while 1:t2 = datetime.datetime.now()if (t2 - t1).microseconds >= 1000:print(t2,t2.microsecond,t1,t1.microsecond,(t2-t1).seconds)breakif __name__ == \'__main__\':from timeit import timeitt = timeit(\'timetime()\', \'from __main__ import timetime\', number=1)print(t)#print (datetime.datetime.now())

输出

(datetime.datetime(2019, 4, 3, 10, 13, 52, 76548), 76548, datetime.datetime(2019, 4, 3, 10, 13, 52, 75547), 75547, 0) 0.00104904174805

补充:Python datetime去除毫秒 返回当前时间

datetime模块返回当前时间

import datetimeif __name__ == \'__main__\':a = datetime.datetime.now().replace(microsecond=0)print(a, type(a))

运算结果:

2020-05-22 12:13:42 <class \’datetime.datetime\’> Process finished with exit code 0

以上为个人经验,希望能给大家一个参考如有错误或未考虑完全的地方,望不吝赐教。

您可能感兴趣的文章:

  • Python 实现毫秒级淘宝抢购脚本的示例代码
  • 使用Python实现毫秒级抢单功能
  • Python完成毫秒级抢淘宝大单功能
赞(0) 打赏
未经允许不得转载:爱站程序员基地 » python 获取毫秒级时间问题的解决