orangephoenix
orangephoenix

Reputation: 1

Recording the time into a text file

I am trying to test how long my battery runs on my raspberry pi. All i need to do is run a while loop until the battery dies. However, I need to record the time that it starts and ends. I would like to save the data into a txt file. My current code is as follows:

import time

file = open('time','w')

x=1
while x==1:
     from datetime import datetime
     now = datetime.now()

file.write(now)
file.close()

If I just print the results in python i will get a result, and the current code makes a file called 'file' but there is nothing saved in the txt file. Any and all help would be appreciated.

Thank you for your time

Upvotes: 0

Views: 689

Answers (3)

agtoever
agtoever

Reputation: 1699

No need to record these times yourself. The Pi (and almost any Linux distribution) writes those events to the /var/log/wtmp file (more about that file here). The last command can retrieve those events (also see the manual entry for last). Try the following:

last -FRx | grep -e 'boot\|shutdown'

Explanation of the flags:

  • -F prints the full date and times - which is handy in your case, because that's what you wanted to know.
  • -R suppresses the hostname in the output. You don't need that.
  • -x shows shutdown en runlevel changes - now that's what you wanted to know.

Finally the grep statement filters out the boot or shutdown messages.

Upvotes: 0

ssm
ssm

Reputation: 5373

I would recomend code that looks like the following:

import time
import datetime.datetime as dt 

initTime = dt.now()

while True:
    with open('time.txt', 'a') as f: 
        f.write( str(dt.now() - initTime) )
    time.sleep(1)

The couple of differences. First, you always open the file in append mode. This way, the file will be flushed every time. Next, it will always update the file with the amount of time elapsed. So even if your raspberry pi shuts down, you should be able to recover it.

Upvotes: 1

mgilson
mgilson

Reputation: 309949

You have an infinite loop which just gets the current time over and over again ... This loop won't break (even if your battery dies ...).

At some point, you need to break the loop or the condition in the while needs to become False. e.g.

from datetime import datetime
while x == 1:
    now = datetime.now()
    break

or

from datetime import datetime
while x == 1:
    now = datetime.now()
    x += 1

Generally speaking, you'll want to look in your system logs for when the computer decided to start up and when it decided to shut down due to lack of battery power ...

Upvotes: 1

Related Questions