解析包含纳秒的日期时间字符串 [英] Parsing datetime strings containing nanoseconds

查看:94
本文介绍了解析包含纳秒的日期时间字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些时间格式为HH:MM :: SS.nano_seconds的日志文件(例如01:02:03.123456789)。我想在python中创建一个日期时间,以便我可以在时间上整齐地做数学运算(例如计算时差)。使用%f,strptime在 microseconds 内运行良好。 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?

推荐答案

您可以看到从来源得知,该对象是 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 likely because computer 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.

后来更新了:现在分别是numpy和pandas对时间戳有(有些不同)支持,其中包括跟踪纳秒的可能性,这通常是很好的解决方案。

Much later update: numpy and pandas now each have (somewhat different) support for timestamps that includes the possibility of tracking nanoseconds, which are often good solutions. See the other answers for how.

Python 3.7+也具有 time.time_ns 和相关功能在 time (< a href = https://www.python.org/dev/peps/pep-0564/ rel = noreferrer> PEP 564 ),但在中仍不支持纳秒日期时间

Python 3.7+ also has time.time_ns and related functions in time (PEP 564), but still no support for nanoseconds in datetime.

这篇关于解析包含纳秒的日期时间字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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