Higher precision logging module time format? [duplicate] - python

This question already has answers here:
Python Logging Module logging timestamp to include microsecond
(7 answers)
Closed 5 years ago.
I am using the logging module from Python and I need to get information about the starting and ending time of different functions calls. For this, I am currently using
formatter = logging.Formatter('%(message)s %(asctime)s.%(msecs)03d %(levelname)s',
datefmt='%H:%M:%S')
Since the calls of a particular function do not last more than a few milliseconds, I would like to get a better precision and have more decimal digits. How can I do this?
I nice solution at: Python logging: use milliseconds in time format

For showing milliseconds:
logging.Formatter(fmt='%(asctime)s.%(msecs)03d',datefmt='%Y-%m-%d,%H:%M:%S')
An extensive example so you can compare:
def formatTime(self, record, datefmt=None):
ct = self.converter(record.created)
if datefmt:
s = time.strftime(datefmt, ct)
else:
t = time.strftime("%Y-%m-%d %H:%M:%S", ct)
s = "%s,%03d" % (t, record.msecs)
return s
Check this answer and also this doc to see all the milliseconds you can use:
import time
current_milli_time = lambda: int(round(time.time() * 1000))
Remember, 1000 milliseconds = 1 second, so you will be able to see 3 digits of milliseconds after the last second

Related

Problems with detecting delay and removing it from .after() in python

I am developing a Tkinter python game - long story short it needs to be able to run at different FPS values. However, I am having trouble maintaining a consistent second length.
I have tried to make it detect lag and take it away from the .after() function:
def UpdatesEveryFrame():
s = time.perf_counter()
# Code here
s = int((time.perf_counter() - s)*1000)
LabelProductionTime3.after(int(1000 / fps) - s, UpdatesEveryFrame)
However, this is unsuccessful. It seems to create an accurate value in milliseconds (usually around 15) but this does not make an accurate second delay. I have tried replacing perf_counter() with time() but this has the same effect.
Because of what the game is based upon, it is essential that there is an accurate second delay. Can you help? Thanks.
If the goal here is precision, then perhaps you should try the time.perf_counter_ns method of the time module, it specifically is made to be more precise than time.perf_counter, and gives time in nanoseconds, further if the time has to be converted back into seconds, it can be done using unit conversion.
Further, the documentation of time.perf_counter method mentions this as well -:
Use perf_counter_ns() to avoid the precision loss caused by the float
type.
def UpdatesEveryFrame():
s = time.perf_counter_ns()/(10 ** 9) # used perf_counter_ns, divided by (10 ** 9) to convert to seconds.
# Code here
s = int((time.perf_counter_ns()/(10 ** 9) - s)*1000) # used perf_counter_ns, divided by (10 ** 9) to convert to seconds.
LabelProductionTime3.after(int(1000 / fps) - s, UpdatesEveryFrame)
EDIT:
There also exists time.monotonic method, designed specifically to measure the time elapsed between two consecutive calls, it returns time in fractional seconds similar to time.perf_counter, so no changes have to be made in the current code except the name of the function itself.
def UpdatesEveryFrame():
s = time.monotonic() # Changed method name.
# Code here
s = int((time.monotonic() - s)*1000)
LabelProductionTime3.after(int(1000 / fps) - s, UpdatesEveryFrame) # Changed method name.
Further, similar to the method time.perf_counter_ns available as a more precise version of time.perf_counter, there also exists a more precise version of the time.monotonic method that returns time in nanoseconds and functions similar to time.monotonic, namely time.monotonic_ns.

python add timestamp to console output

I would like to add a timestamp for each output in console.
My tool is using selenium and clicks on specific things on a website.
when specific events happen (for example see below code block) I would like to print it with a timestamp.
print(f'Bought player: {str_player_name} for {int_player_price}')
print(f'Estimated profit: {int_expected_profit}')
print(f'Player counter {str(int_players_bought)}/{str(int_max_players_bought)}')
I have many prints in my console - is there a way to automatically add a timestamp to each print('')?
add this to your code
from datetime import datetime
print(datetime.now().strftime(%H:%M:%S))
You could define a printf function for that too
from datetime import datetime
def printf(*arg, **kwarg):
timestamp = datetime.now().strftime("%H:%M:%S")
print(timestamp, *arg, **kwarg)
Then, replace all your print call into printf.
But what you are trying to do is the job of the logger. I suggest you should add loggers to your code before it becomes complicated.

How can you update local time from the datetime module?

I am writing a program that uses a while loop to check if it is a certain time, and if it is that certain time, it prints a statement. I have all the if-statements set up, but the time does not update once the program starts (if I start the program at 6 pm, it will always output 6 pm for local time). Is there a way to update the time within the while loop?
I tried to research some additional functions/methods to datetime, but from what I have seen, I have not been able to find any that updates the time while the program is running. Additionally, forums regarding datetime and locale time that I have found on stackoverflow are commonly ones that just explain how to obtain the locale time once (ex, Python datetime module current time in HR:MIN:SEC). Other forums regarding locale times that I have found also tended to be in different languages, particularly C# and PHP. Please correct me if there is another forum that answers my question!
from datetime import date
from datetime import time
from datetime import datetime
import time
import webbrowser
now = datetime.now()
sleep = False
today = date.today()
roundCheck = 0
print("Awaiting time check...")
while sleep != True:
print('Up here...')
if roundCheck != 0:
print('Stuck in time...')
time.sleep(60)
print('Time is done')
if str(now.strftime('%H')) == '20' and str(now.strftime('%M')) == '05':
print('Now the while loop will end')
sleep = True
roundCheck = 1
print('Another round has passed')
print('Outside while loop')
When the time is 20:05, sleep should be set to true and the print statement outside the while loop can be executed. However, when I start the program at an earlier time (20:00, for example), it only uses that time for checking now.strftime().
now never changes. You simply need to put now = datetime.now() in the while loop.

How can I set time in this Python code? [duplicate]

This question already has answers here:
How do I get a Cron like scheduler in Python?
(9 answers)
Closed 4 years ago.
def initialize(context):
g.security = '000001.XSHE'
set_benchmark('000300.XSHG')
def handle_data(context,data):
security = g.security
order(security, 100)
I want operation this code at 10:00 o'clock, how can write the code?
You can use the sched module or simply loop through datetime, although as AChampion points out, on a *nix platform, it's easier to use cron.
This stackoverflow question does into more detail about sched and datetime.
Essentially:
from datetime import datetime as dt
while True:
if dt.now().hour == 10: # for 10 o'clock
initialize(context)
handle_data(context,data)
time.sleep(60) # Minimum interval between task executions
else:
time.sleep(10) # The else clause is not necessary but would prevent the program to keep the CPU busy.

Does Python's time.time() return a timestamp in UTC? [duplicate]

This question already has answers here:
Does Python's time.time() return the local or UTC timestamp?
(9 answers)
Closed 7 years ago.
I need to generate a UNIX timestamp in UTC time so I'm using time.time() to produce it.
Do I need to do anything else or is the timestamp automatically in UTC?
Technically, time.time() doesn't specify, and practically, at least in CPython, it returns a timestamp in whatever format is used by the underlying standard C library's time function.
The C standard (which isn't freely available) doesn't say whether this is GMT, and neither does the POSIX standard. It just says:
The time() function shall return the value of time in seconds since the Epoch.
… without saying anything about timezone, except that you can pass it to localtime or gmtime to get a "broken-down time" in local or GMT timezones.
So, this is platform-specific. A platform can return anything it wants for time, as long as it does so in a way that makes localtime and gmtime work properly.
That being said, it's usually going to be GMT—or, rather, either UTC (Windows), or UTC-except-for-leap-seconds (most other platforms). For example, FreeBSD says:
The time() function returns the value of time in seconds since 0 hours, 0 minutes, 0 seconds, January 1, 1970, Coordinated Universal Time, without including leap seconds.
OS X and most other *BSDs have the same manpage, Windows and linux/glibc also specifically return UTC (with or without leap seconds), etc.
Also, the Python documentation says:
To find out what the epoch is, look at gmtime(0).
Putting that together with the definitions for time and gmtime, it would be much more work for a platform to return local timestamps than GMT. (That being said, this statement can't be all that authoritative, because it's actually not quite true for any POSIX platform, thanks to leap seconds.)
time.time() returns seconds since epoch, so it doesn't define which time standard or zone is being used.
Convert to time standards using:
time.localtime([secs]) - Local time as defined by your operating system
time.gmtime([secs]) - UTC
They both return a time.struct_time.
>>> t = time.time()
>>> time.localtime(t)
time.struct_time(tm_year=2013, tm_mon=5, tm_mday=15, tm_hour=2, tm_min=41, tm_sec=49, tm_wday=2, tm_yday=135, tm_isdst=1)
>>> time.gmtime(t)
time.struct_time(tm_year=2013, tm_mon=5, tm_mday=15, tm_hour=0, tm_min=41, tm_sec=49, tm_wday=2, tm_yday=135, tm_isdst=0)

Categories