nanotime (jbenet's library)

0.5.2 · abandoned · verified Thu Apr 16

nanotime is a Python library that provides a time object with nanosecond precision, storing time as a 64-bit UNIX timestamp (nanoseconds since epoch). It aims to offer a portable, easy-to-process time type with higher precision than standard Unix timestamps. This library was last updated in 2011 and provides a distinct approach to high-precision time compared to the `time.time_ns()` function introduced in Python 3.7.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to create a `Nanotime` object, convert it to an integer nanosecond timestamp, convert it to and from a standard `datetime` object, and measure elapsed time.

from nanotime import Nanotime
import datetime

# Get current time with nanosecond precision
now = Nanotime.now()
print(f"Current nanotime: {now}")

# Convert to nanoseconds (integer)
ns_since_epoch = int(now)
print(f"Nanoseconds since epoch: {ns_since_epoch}")

# Convert to datetime object (loses nanosecond precision beyond microseconds)
dt_obj = now.datetime()
print(f"Converted to datetime: {dt_obj}")

# Create from a datetime object
some_dt = datetime.datetime(2023, 1, 1, 12, 30, 0, 123456)
nt_from_dt = Nanotime.from_datetime(some_dt)
print(f"Nanotime from datetime: {nt_from_dt}")

# Calculate duration
import time
start_nt = Nanotime.now()
time.sleep(0.001) # Simulate some work
end_nt = Nanotime.now()
delta_ns = int(end_nt) - int(start_nt)
print(f"Time elapsed (nanoseconds): {delta_ns}")

view raw JSON →