在Python中格式化纳秒 [英] Format Nanoseconds in Python

查看:2634
本文介绍了在Python中格式化纳秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些时间格式为HH:MM :: SS.nano_seconds(例如01:02:03.123456789)的日志文件。我想在python中创建一个datetime,所以我可以整齐地做数学(例如花时间差异)。使用%f,strptime适用于微秒。 Python日期时间和时间模块真的不支持纳秒吗?
谢谢

I have some log files with times in the format HH:MM::SS.nano_seconds (e.g. 01:02:03.123456789). I would like to create a datetime in python so I can neatly do math on the time (e.g. take time differences). strptime works well for microseconds using %f. Do the Python datetime and time modules really not support nanoseconds? Thanks

推荐答案

你可以看到这个datetime对象不支持比微秒更精细的东西。正如Mike Pennington在评论中指出的,这是因为实际的硬件时钟不太精确。维基百科说, HPET 的频率至少为10 MHz,这意味着每100纳秒一个刻度。

You can see from the source that datetime objects don't support anything more fine than microseconds. As pointed out by Mike Pennington in the comments, this is because actual hardware clocks aren't nearly that precise. Wikipedia says that HPET has frequency "at least 10 MHz," which means one tick per 100 nanoseconds.

如果你可以扔掉最后三位数字(这可能并不太有意义),你可以通过将输入字符串切成只有小数点后六位,并用%f 解析。否则,您将不得不自己实现减法。

If you can live with throwing out the last three digits (which probably aren't too meaningful anyway), you could parse this by just slicing the input string to have only six digits after the decimal point and parsing with %f. Otherwise, it looks like you'll have to implement the subtraction yourself.

这篇关于在Python中格式化纳秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆