Hardware Reference
In-Depth Information
Why not try it yourself in an interactive Python session? Type the following
import datetime
datetime.datetime.now().strftime(“Today is: %A %d %B %Y. ;
The time is: %I:%M:%S %p”)
Create a format string to format the time and date so that if now was 6:15 p.m. on the 14th of
March, it would be displayed as 1815 2013-03-14.
There are other codes too. Find out what %j does.
You will notice that there is no code to display the time in milliseconds. As the time between
beams breaking and unbreaking can be less than a second, a way to format the time in milli-
seconds needs to be created by the programmer.
he datetime.datetime object has the attribute microsecond . Because there are 1000
microseconds in a millisecond, this number is divided by 1000, rounded to the nearest whole
number by the int and round functions and then converted to a string and concatenated to
the end of the formatted date/time.
Writing to a File
he logEvent function is called to record an event to a ile. You will see later that in the
program initialisation a ile object called logFile is created:
#generate and record an event to file
def logEvent(sensor, state):
logFile.write(str(sensor) + “,” + str(state) + ;
“,” + getFormattedTime() + “\n”)
he logEvent function builds the string to be written to the ile and then passes it to the
write function of the logFile object. Which beam and how it changed are passed as argu-
ments to the function and stored separated by commas. he end of the string written is an
“\n” , which is a special character code to create a new line in Linux.
The code for a new line varies across operating systems. Files in Microsoft Windows require
the code “\r\n” instead of just “\n” .
 
Search WWH ::




Custom Search