简体   繁体   中英

Python timestamp in precision of milliseconds

I need to output a timestamp for a .csv file of the current time in milliseconds. Right now I have:

localTime = time.localtime(time.time())
now = time.localtime(time.time())
currTime = time.time()
now = time.strftime("\"%Y-%m-%d %H:%M:%S.%f\"", time.localtime(currTime))

doing it this way will output the timestamp in the following format: "2017-05-09 10:13:33.%f" this obviously is not correct. Ive heard that time.time only goes as precise as a second, but have also heard that it can support microseconds. Can somebody clear this up for me or show me the proper way to format this code to get a timestamp in the needed format? (2017-05-09 10:13:33.100) for example

A quick solution would be:

t=time.time()
millis = int((t - int(t))*1000)

As you said, the problem is that time doesn't necessarily give you the precision you want[1]. datetime would be a better option:

from datetime import datetime

now = datetime.utcnow()  # or datetime.now(your_timezone)
formatted = now.strftime("%Y-%m-%d %H:%M:%S.%f")
print(formatted)

[1] Both in python 2.x and 3.x, according to the docs :

Note that even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second. While this function normally returns non-decreasing values, it can return a lower value than a previous call if the system clock has been set back between the two calls.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM