Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use number of seconds since the UNIX Epoch as date format in logging

The docs for logging.basicConfig say:

datefmt - Use the specified date/time format, as accepted by time.strftime().

However, if I have a look at the docs for time.strftime(), the UNIX Epoch timestamp isn't even mentioned there.


Update: If I'm using %s as described in the manpage for strftime(3), it works with Linux, but not with Windows.

import time
time.strftime('%s')

results in

ValueError: Invalid format string

So I'm looking for a platform-independent way to use the number of seconds since the UNIX Epoch as date format in logging.

like image 730
finefoot Avatar asked Sep 11 '25 13:09

finefoot


1 Answers

It's not possible to do this with asctime for certain, since the behavior of strftime regarding supported format strings is platform-dependent.

There is a paragraph in the docs in the section "strftime() and strptime() Behavior" about this:

The full set of format codes supported varies across platforms, because Python calls the platform C library’s strftime() function, and platform variations are common. To see the full set of format codes supported on your platform, consult the strftime(3) documentation.

https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior


However, disregarding asctime, you can still use the number of seconds since the UNIX Epoch in your logginng format string. There is another attribute called created:

%(created)f - Time when the LogRecord was created (as returned by time.time()).

https://docs.python.org/3/library/logging.html#logrecord-attributes

Since time.time() works on both Linux and Windows, you can just use created instead of asctime in the logging format string.

like image 167
finefoot Avatar answered Sep 14 '25 03:09

finefoot