Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to convert datetime object to time_ns

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading