time.strftime('%m-%d-%Y %H:%m:%S') to log is out of order
Simon Forman
sajmikins at gmail.com
Tue Jul 21 19:59:21 EDT 2009
On Jul 21, 5:53 pm, davidj411 <davidj... at gmail.com> wrote:
> On Jul 21, 5:29 pm, Simon Forman <sajmik... at gmail.com> wrote:
>
>
>
> > On Jul 21, 5:00 pm, davidj411 <davidj... at gmail.com> wrote:
>
> > > I am using a recursive function to print the time and a few other
> > > things on each pass. ( the function calculates size of file that is
> > > being transferred and if not 100 % copied, it waits 20 secs and checks
> > > again).
>
> > > i would expect the time to be correct anytime it is used:
>
> > > <--code below -->>
> > > print time.strftime('%m-%d-%Y %H:%m:%S')
> > > <--code above -->>
>
> > > here is an example of what i am seeing:
>
> > > 16:07:16
> > > 16:07:36
> > > 16:07:56
> > > 16:07:16
> > > 16:07:36
> > > 16:07:56
> > > 16:07:16
> > > 16:07:36
> > > 16:07:56
>
> > Your output doesn't match your format string:
>
> > In [1]: import time
>
> > In [2]: print time.strftime('%m-%d-%Y %H:%m:%S')
> > 07-21-2009 17:07:16
>
> > There's no way to tell why your output times seem to repeat without
> > seeing the code that surrounds your "print time.strftime('%m-%d-%Y %H:
> > %m:%S')" line.
>
> sorry, yes, i did manually filter the output.
>
> here is the function:
>
> def log_out(msg,servername='std.out'):
> print msg
> open(log_dir + '\\' + servername + ".log",'a').write(servername + "-"
> + time.strftime('%m-%d-%Y %H:%M:%S') + " " + msg+'\n')
>
> on each pass, it should output the newer time (whether recursive or
> not, right) ?
Well, as Piet van Oostrum pointed out, your problem in the first code
you posted was that you used '%m' rather than '%M' for the minutes.
(Good eye Van Oostrum!) But now in this function you seem to have the
correct '%M' field. Are you still having the same output after
changing that?
In any event, here's a rewritten version of that function that's a
little cleaner, FWIW.
from os.path import join
from time import strftime
format = '%m-%d-%Y %H:%M:%S'
def log_out(msg, servername='std.out'):
print msg
msg = "%s - %s %s\n" % (servername, strftime(format), msg)
log_file = open(join(log_dir, servername + ".log"), 'a')
try:
log_file.write(msg)
finally:
log_file.close()
But why not just use the logging module?
More information about the Python-list
mailing list