working with times and dates


8 posts
by stevep » Sun Jun 10, 2012 6:39 pm
This might belong in the beginners section, but it's Python so here goes. I've got a gps dongle connected, which is returning all the usual data, including time. I've written a few lines to extract the time (formatted as seconds from the epoch, so something like 1339324998.14). This then has to be converted to something more user friendly (- I struggled with this bit and there is probably a better way).

two simple questions:
1. The Hour and Minute values returned are in the format '18' and '30' including the quote marks. I don't know if this is a Python thing, but I want simple numerical values, not a text string. How do I strip out the quote marks and ensure that I am left with a numerical value (one that I can do some maths with at a later date).

2. When I run the code in a terminal window, it obviously loops round, looking at the gps dongle every few seconds and displaying the results. I want to stop the program running, but keep the last set of results displayed in the terminal window so I can copy and paste the output. Ctrl+C just shuts it completely. Any suggestions?

Answers in words of one syllable or less please, it's taken me all day to write the following and get it to work:
Code: Select all
#timetest1.py
#             
from datetime import datetime
import time, os, gps, calendar
session = gps.gps(host="localhost", port="2947")
session.poll()
session.stream()

while 1:
   os.system("clear")
   session.poll()
   print "Just for info:"
   print "time GPS " ,  session.fix.time
   print "time utc " ,  session.utc, session.fix.time
   
   print "***************"
   
   timestamp = session.fix.time
   print "Simple check for syntax:"
   print repr(timestamp)
   
   
   print "****************"
   print "[1]"
   time_gmtuple = time.gmtime(timestamp)
   print "This is the time according to the GPS dongle"
   print repr(time_gmtuple) #***
   
   
   print "******************"
   print "[2]"
   print "As for [1] but converted to a sort of string"
   dt_obj = datetime.utcfromtimestamp(timestamp)
   print repr(dt_obj)
   
   print "******************"
   print "[3]"
   print "Extract the <Hours> value from the string"
   extract_hrs = dt_obj.strftime("%H")
   print repr(extract_hrs)
   
   print "******************"
   print "[4]"
   print "Extract the <Minutes> value from the string"
   extract_min = dt_obj.strftime("%M")
   print repr(extract_min)

   for i in session.satellites:
      print "t", i
   time.sleep(5)
Posts: 71
Joined: Sat Dec 24, 2011 10:12 am
by yeahbox » Sun Jun 10, 2012 11:00 pm
1) If you know that the value you want to convert really is an integer, you can just use int() to convert it, like for example int('21') will result in the integer 21. This will raise an exception if it can't be converted.

2) You could use a try-except:
Code: Select all
import time

try:
    while True:
        hour = time.strftime("%H")
        print hour, type(hour)
        hour = int(hour)
        print hour, type(hour)
        time.sleep(1)
except KeyboardInterrupt:
    print "Good bye!"
Posts: 36
Joined: Sun May 27, 2012 10:35 pm
Location: Manchester, UK
by bhoga » Sun Jun 10, 2012 11:29 pm
If you just want an integer hour or minute value, you can get it easily once you have a datetime object:

Code: Select all
dt_obj.hour
dt_obj.minute


In a python console you can type

Code: Select all
dir(dt_obj)


To get a list of methods and properties of any variable. You can try help(object) too.

Have fun!
User avatar
Posts: 10
Joined: Sun Jun 03, 2012 7:33 pm
Location: Brighton, UK
by texy » Mon Jun 11, 2012 6:38 am
Which GPS dongle do you have?

Texy
"2.8inch TFT LCD + Touch screen" add-on boards for sale here :
http://www.raspberrypi.org/phpBB3/viewtopic.php?f=93&t=65566
50p goes to the Foundation ;-)
Forum Moderator
Forum Moderator
Posts: 2339
Joined: Sat Mar 03, 2012 10:59 am
Location: Berkshire, England
by stevep » Mon Jun 11, 2012 6:44 am
Really helpful answers, thanks guys. I'll have a play later today.

The dongle is a Bluenext 903s, around £16 from Scan Computers (uk).
Posts: 71
Joined: Sat Dec 24, 2011 10:12 am
by kasperl » Mon Jun 11, 2012 10:32 am
As for doing maths on the times, it might be easier to do that in seconds from epoch than in hour,minutes kinds of stuff.
Posts: 90
Joined: Fri Jan 06, 2012 6:20 pm
by wrhii » Sun Jun 17, 2012 7:28 pm
Any easy method of working with Date/Time is to use:
Code: Select all
from datetime import date, timedelta

def elapse_time(starttime):
    result=[]
    curr_time=datetime.datetime.now()   # capture current time of execution.
    result=curr_time-starttime
    return result


starttime is set using the following:
Code: Select all
stime=datetime.datetime.now()   # capture start time of execution.

The elapse_time function will give you...the elapsed time, and can be called with code such as used here.
Code: Select all
print 'Elapsed time: %s' % ('',elapse_time(stime))

The time printed is in a user meaningful format. Other format options are available, you will need to review the format options for datetime.

Lots of options on what you see when using datetime.

Alternately, you can do date arithmetic with the "date" function and timedelta. The following code sample will take today's date, and subtract some number of days, and then set the result into del_basedate.
Code: Select all
del_basedate = date.today() - timedelta(days=cmd.age)
Posts: 66
Joined: Fri Nov 18, 2011 1:47 am
by karl101 » Wed Jun 20, 2012 2:00 pm
hello,
is this of any use?
Code: Select all
#! /usr/bin/python

import time

#time from the gps, needs to be a floating number, not a string
epochTime = float("1339324998.14")

#convert into a python tuple format
pyTime    = time.gmtime(epochTime)
print pyTime

#convert into a string (SQL reverse date style)
# http://docs.python.org/library/time.html#time.strftime
sqlDate   = time.strftime("%Y-%m-%d %H:%M:%S", pyTime)
print sqlDate
I have always found when doing calculations with dates and time, is to keep them in a date/time format, like pyTime above, rather than convert them into integers.


detecting a keypress seems to be more difficult than it should be, I found this and it seems to work:
Code: Select all
#! /usr/bin/python
## taken from: http://www.darkcoding.net/software/non-blocking-console-io-is-not-possible/

import sys
import select
import tty
import termios

def isData():
  return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], [])

old_settings = termios.tcgetattr(sys.stdin)
try:
  tty.setcbreak(sys.stdin.fileno())

  i = 0
  while 1:
    print i
    i += 1

    if isData():
      c = sys.stdin.read(1)
      if c == '\x1b':         # x1b is ESC
        break
                                                                                                                           
finally:
  termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)


Karl.
Posts: 63
Joined: Wed Jan 11, 2012 10:09 am