unknowntothem
Posts: 5
Joined: Thu Jul 26, 2018 6:30 am

Recording micro-seconds for more than 1 second

Thu Jul 26, 2018 6:40 am

Hello All,

Apologies, I guess this is more of a python question but it's for my first raspberry pi project so hope that someone can advise.

I am reading 4 sensors at 600 micro-seconds per sample. At the same time I am adding a timestamp to each sample. I have used the following code which times 999 999 micro-seconds then resets. Does anyone know how to extend this timer to 60 seconds (i.e. 60 999 999)? Any advise would be appreciated. I've only added the important code below, will add full code if required.

Code: Select all

from datetime import datetime

while True:
	now = datetime.now()
	print(now.microsecond)
	

User avatar
joan
Posts: 14748
Joined: Thu Jul 05, 2012 5:09 pm
Location: UK

Re: Recording micro-seconds for more than 1 second

Thu Jul 26, 2018 9:36 am

Why not use the time() method from module time?

That returns the number of microseconds since the Unix epoch.

Code: Select all

import time
now = time.time()

User avatar
lmarmisa
Posts: 1260
Joined: Thu Feb 14, 2013 2:22 am
Location: Jávea, Spain

Re: Recording micro-seconds for more than 1 second

Thu Jul 26, 2018 11:20 am

Try this code:

Code: Select all

from datetime import datetime, date, time

while True:
	now = datetime.now()
	usec = now.second * 1000000 + now.microsecond
	print(usec)
If you prefer to get an string, try this alternative:

Code: Select all

usec = "%02d%06d" %(now.second, now.microsecond)
NOTE: the range will be from 00000000 to 59999999.

User avatar
davidcoton
Posts: 4653
Joined: Mon Sep 01, 2014 2:37 pm
Location: Cambridge, UK

Re: Recording micro-seconds for more than 1 second

Thu Jul 26, 2018 8:19 pm

joan wrote:
Thu Jul 26, 2018 9:36 am
Why not use the time() method from module time?

That returns the number of microseconds since the Unix epoch.

Code: Select all

import time
now = time.time()
+1 for Joan's idea. Use the proper tool for the job, so that you:
  1. Avoid problems caused by the potentially variable start time within the second and minute, and therefore with the value of the time returning to zero during your sampling.
  2. Future proof your code so that you can change the overall timer period without issues.
  3. Write code that can be re-used in similar but different projects.
Signature retired

unknowntothem
Posts: 5
Joined: Thu Jul 26, 2018 6:30 am

Re: Recording micro-seconds for more than 1 second [SOLVED]

Mon Jul 30, 2018 1:02 pm

Hello All,

Thank you very much for the responses, all of the ideas worked. I ended up using lmarmisa's option. just because I didn't lose any sampling speed and the output format was suitable with my current MATLab code.

Return to “Beginners”