0

I have the following problem I need to convert some datetime object to time_ns (present in time)

all I can find is to convert the now datetime to that fixed nanoseconds number (i understand that it is calculated from a fixed date in 1970)

import time
now = time.time_ns()

all I want is to convert some normal datetime object to that fixed nanoseconds number

from datetime import datetime
x = datetime(2022, 2, 22, 15, 41, 50)

i don't want to be restricted to only now dates. is there some function in the library that does that? for the moment i cannot find anything

thank you very much

EricD1990
  • 33
  • 1
  • 5
  • you basically want [Unix time](https://en.wikipedia.org/wiki/Unix_time). datetime objects have a method [timestamp()](https://docs.python.org/3/library/datetime.html#datetime.datetime.timestamp) that gives you that in *seconds* since the Unix epoch, 1970-01-01 midnight UTC. Multiply by 10^9 to get nanoseconds. – FObersteiner Mar 02 '22 at 09:49

2 Answers2

1

Since python 3.3 datetime has a timestamp function. Make sure to replace the timezone, otherwise local timezone will being taken and if you want to have nanosecond number you can multiply the seconds number.

from datetime import datetime; 
print(datetime(2022,2,22,15,41,50).replace(tzinfo=timezone.utc).timestamp()*10**9)
Stev
  • 416
  • 4
  • 11
0

Note that if you're just trying to convert time.time() or time.time_ns() into a date and time instead, use time.localtime() or time.gmtime().

See the various reference documentation descriptions for each of those functions here: https://docs.python.org/3/library/time.html#time.time:

Examples:

>>> import time
>>> time.time_ns()
1691443244384978570
>>> time.localtime(time.time_ns()/1e9)
time.struct_time(tm_year=2023, tm_mon=8, tm_mday=7, tm_hour=14, tm_min=20, tm_sec=57, tm_wday=0, tm_yday=219, tm_isdst=0)
>>> time.time_ns()/1e9
1691443263.0889063
>>> time.localtime(time.time())
time.struct_time(tm_year=2023, tm_mon=8, tm_mday=7, tm_hour=14, tm_min=23, tm_sec=22, tm_wday=0, tm_yday=219, tm_isdst=0)

That's all from my bigger answer here: High-precision clock in Python

Gabriel Staples
  • 36,492
  • 15
  • 194
  • 265