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:
- Convert the string to a datetime format:
date = '19551231'
date = datetime.datetime.strptime(date, '%Y%m%d')
- Convert to DatetimeWithNanoseconds:
nano = DatetimeWithNanoseconds(date.year, date.month, date.day, date.hour, date.minute, date.second, nanosecond=0)
Related Topics
Paramiko Ssh Die/Hang with Big Output
How to Dynamically Compose an or Query Filter in Django
Underscore _ as Variable Name in Python
Escape String Python for MySQL
How to Compare String and Integer in Python
How to Sort Objects by Multiple Keys
How to Add a String in a Certain Position
How to Change Index of a for Loop
How to Make a Surface with a Transparent Background in Pygame
How to Escape Strings for SQLite Table/Column Names in Python
Filling in Login Forms in Instagram Using Selenium and Webdriver (Chrome) Python Osx
Django Db Settings 'Improperly Configured' Error
How to Plot Multiple Functions on the Same Figure, in Matplotlib
How to Retrieve Items from a Dictionary in the Order That They'Re Inserted
Python JSON Parser Allow Duplicate Keys
Share Large, Read-Only Numpy Array Between Multiprocessing Processes