Parsing Datetime Strings Containing Nanoseconds

Parsing datetime strings containing nanoseconds

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.

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.


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+ also has time.time_ns and related functions in time (PEP 564), but still no support for nanoseconds in datetime.

How to convert a string to a DatetimeWithNanoseconds format with python?

I learned that from a datetime format it is easy to extract hours for example just by calling date.hour (same for year, month, etc).

Knowing this, the way to convert a string to a DatetimeWithNanoseconds format takes these 2 easy steps:

  1. Convert the string to a datetime format:
date = '19551231'
date = datetime.datetime.strptime(date, '%Y%m%d')

  1. Convert to DatetimeWithNanoseconds:
nano = DatetimeWithNanoseconds(date.year, date.month, date.day, date.hour, date.minute, date.second, nanosecond=0)


Related Topics



Leave a reply



Submit