Travis
Travis

Reputation: 1

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

Upvotes: 0

Views: 2465

Answers (2)

marianosimone
marianosimone

Reputation: 3606

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.

Upvotes: 0

allo
allo

Reputation: 4236

A quick solution would be:

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

Upvotes: 1

Related Questions