Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get POSIX/Unix time in seconds and nanoseconds in Python?

Tags:

python

posix

time

I've been trying to find a way to get the time since 1970-01-01 00:00:00 UTC in seconds and nanoseconds in python and I cannot find anything that will give me the proper precision.

I have tried using time module, but that precision is only to microseconds, so the code I tried was:

import time  print time.time() 

which gave me a result like this:

1267918039.01 

However, I need a result that looks like this:

1267918039.331291406 

Does anyone know a possible way to express UNIX time in seconds and nanoseconds? I cannot find a way to set the proper precision or get a result in the correct format. Thank you for any help

like image 738
Bill Avatar asked Mar 06 '10 23:03

Bill


People also ask

Can Python handle nanoseconds?

On Python 3, the time module gives you access to 5 different types of clock, each with different properties; some of these may offer you nanosecond precision timing.

How do you make a nano second in Python?

time_ns() method of Time module is used to get the time in nanoseconds since the epoch. To get the time in seconds since the epoch, we can use time. time() method. The epoch is the point where the time starts and is platform dependent.

How do you convert time in Unix Python?

To manipulate dates and times in Python, you can use the datetime module. Use datetime. fromtimestamp() of the datetime module to convert Unix time (Epoch time) to datetime object.

How do you measure time in nanoseconds Python?

To measure the elapsed time between two code instances in nanoseconds, you can use the time. time_ns() function, which returns the time in nanoseconds since the epoch in floating-point number.


1 Answers

Since Python 3.7 it's easy to achieve with time.time_ns()

Similar to time() but returns time as an integer number of nanoseconds since the epoch.

All new features that includes nanoseconds in Python 3.7 release: PEP 564: Add new time functions with nanosecond resolution

like image 106
vishes_shell Avatar answered Sep 19 '22 15:09

vishes_shell