outputting time in microseconds or milliseconds

Dave Angel davea at davea.name
Fri Aug 2 08:08:33 EDT 2013


matt.doolittle33 at gmail.com wrote:

> Hey everybody,
>
> I am using 2.7 on Ubuntu 12.10.

and what version of Python are you using?  I don't know if it matters,
but it's useful to always supply both Python version and OS version.

>  All I need to do is to print time with the microseconds.  I have been
> looking at the docs and trying things for about half a day now with
> no success. Currently my code looks like this:
>
>         #  write date and time and microseocnds
>         self.logfile.write('%s\t'%(str(strftime("%Y-%m-%d", ))))
>         self.logfile.write('%s\t'%(str(strftime("%H:%M:%S", ))))

You've already got a problem:  since this has two (implicit) calls to
localtime().  If this happens near enough to midnight, then your date
could be for one day, but the time for the following day.

You need to make a single call to get the time, and then format it into
one or more fields.  if you didn't need sub-second information, it could
have been done by just using a longer spec for strftime().


>         self.logfile.write('%s\t'%(str(time())))

When I test str(time()) I get an output like this:
 1375444314.484557
I can't imagine how you would get that third column from the line you
quote above.

>
> the output looks like this:
>
> 2013-08-02	06:01:43       00:00:00	
> 2013-08-02	06:01:43       00:00:00					
> 2013-08-02	06:01:43       00:00:00				
> 2013-08-02	06:01:43       00:00:00						
> 2013-08-02	06:01:43       00:00:00						
> 2013-08-02	06:01:43       00:00:00				
> 2013-08-02	06:01:43       00:00:00						
> 2013-08-02	06:01:43       00:00:00						
> 2013-08-02	06:01:43       00:00:00						
> 2013-08-02	06:01:44       00:00:00					
> 2013-08-02	06:01:44       00:00:00				
>
> as you can see in the 2nd column the observations occur with 'fractional second' frequency, up to 8 or 9 per second.  You can also see my latest attempt to get the microseconds in the third column is not working.  It would really be great if python had a way to just tack the microseconds (actually i think milliseconds would be better) on to the second (in the 2nd column) as a fraction. If this is not possible I need the extra write statement for just the microseconds (millisecond if possible). 
>


now = time()   #make a single call to get the time in seconds (float)
localnow = localtime(now)

print(strftime("%Y-%m-%d\t%H:%M:%S\t", llocalnow))
print(now-int(now))  #obviously you should format this to get the
desired layout

-- 
DaveA





More information about the Python-list mailing list