CSc 7003, Programming for Data Science (Summer 2022)

Program 5 - Time Class

Write a Python program to implement the Time class.

class Time(object):
  def __init__(self, hour, minute, second, ampm):
    self._hour = hour
    self._minute = minute
    self._second = second
    self._ampm = ampm  # midnight will be AM!!; ampm = 'AM' or 'PM'

  # This function returns the time 1 second after time denoted by self
  def next(self):

  # This function returns the time 1 second before time denoted by self
  def previous(self):

  # This function returns the time nseconds seconds after time denoted by self
  def add(self,nseconds):
    t = Time(self._hour,self._minute,self._second,self._ampm)
    for i in range(nseconds):
      t = t.next()  
    return t

  # This function returns the time nseconds seconds before time denoted by self
  def sub(self,nseconds):

  # This function returns number of seconds that have elapsed after midnight until time denoted by self
  def seconds_from_midnight(self):

  # This function returns True if time denoted by self is AFTER time denoted by t
  def after(self,t):

  # This function returns True if time denoted by self is EQUAL TO time denoted by t
  def equals(self,t):
    return ((self._second == t._second) and
            (self._minute == t._minute) and
            (self._hour == t._hour) and
            (self._ampm == t._ampm))

  # This function returns True if time denoted by self is BEFORE time denoted by t
  def before(self,t):

  # This function returns the number of seconds between time denoted by self and time denoted by t
  def seconds_between(self,t):

  # This function returns a string representation of the time denoted by self
  def __str__(self):
    def two_spaces(n):
      if n<10:
        return '0'+str(n)
      else:
        return str(n)
    return two_spaces(self._hour)+":"+two_spaces(self._minute)+":"+ \
           two_spaces(self._second)+" "+self._ampm

Time.py

DriverTime.py