How to get UTC timestamp in Python WITH ALL DIGITS

Viewed 89

I am using this in my Python Script

datetime.datetime.utcnow().isoformat()

in order to print timestamps every 5 seconds (and also power values). I want to later use the timestamps and power values to create graphs in Power BI. The problem is that sometimes the timestamp printed is like this (see error too)

DataFormat.Error: The provided input could not be analyzed as a DateTime value.
Details
    2019-6-16T20:58:5.488

The problem is that the seconds are 5.488 and not 05.488

I have not found a solution in Power BI, so I thought maybe there is a way to actually print it like this in the Python script from the beginning

2019-6-16T20:58:05.488

Any ideas?

3 Answers

you can use .strftime to set a format yourself.

try this:

import datetime

print(datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S.%f"))

Output:

2019-06-27T11:18:03.663386

you can do it by just formatting the datetime string like so:

say your time is now

import datetime as dt

cur_time = dt.datetime.now()

print(print(str(cur_time).replace(' ','T')[:-3])

this produces:

2019-06-27T14:21:10.853

Instead of isoformat() use strptime() dt = datetime.datetime.strftime("21/11/06 16:30.1321", "%d/%m/%y %H:%M.%ffffff") In your case something like dt = datetime.datatime.strptime(datetime.datetime.utcnow(), "%d/%m/%y %H:%M.%f")

Here you have all about datatime codes for formating: https://www.programiz.com/python-programming/datetime/strftime

Related