Home > other >  how to convert datetime object to time_ns
how to convert datetime object to time_ns

Time:03-03

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

CodePudding user response:

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)
  • Related