Python datetime.time() Examples

The following are 30 code examples for showing how to use datetime.time(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module datetime , or try the search function .

Example 1
Project: kw_condition   Author: coreanq   File: main.py    License: MIT License 6 votes vote down vote up
def isTradeAvailable(self):
        # 매수 가능 시간 체크 
        # 기본 정보를 얻기 위해서는 장 시작전 미리 동작을 시켜야 하고 매수를 위한 시간은 정확히 9시를 맞춤 (동시호가 시간의 매도 호가로 인해 매수 됨을 막기 위함)
        ret_vals= []
        current_time = self.currentTime.time()
        for start, stop in AUTO_TRADING_OPERATION_TIME:
            start_time =  datetime.time(
                            hour = 9,
                            minute = 0 )
            stop_time =   datetime.time( 
                            hour = stop[0],
                            minute = stop[1])
            if( current_time >= start_time and current_time <= stop_time ):
                ret_vals.append(True)
            else:
                ret_vals.append(False)
                pass

        # 하나라도 True 였으면 거래 가능시간임  
        if( ret_vals.count(True) ):
            return True
        else:
            return False
        pass 
Example 2
Project: InsightAgent   Author: insightfinder   File: collectdReportMetrics.py    License: Apache License 2.0 6 votes vote down vote up
def remove_old_files(directory, filetype):
    now = datetime.datetime.now()
    now_time = now.time()
    # time between which each day the deletion is done
    if datetime.time(06, 30) <= now_time <= datetime.time(20, 35):
        # data directory path
        data_file_path = directory
        # data_file_path = os.path.join(homepath,datadir)
        now = time.time()
        for f in os.listdir(data_file_path):
            data_file = os.path.join(data_file_path, f)
            # check files older than 3 days
            if os.stat(data_file).st_mtime < now - 2 * 86400:
                # only delete csv files
                if filetype is None:
                    if os.path.isfile(data_file):
                        os.remove(data_file)
                else:
                    if str(filetype) in str(os.path.splitext(data_file)[1]):
                        # print data_file
                        if os.path.isfile(data_file):
                            os.remove(data_file) 
Example 3
Project: rets   Author: opendoor-labs   File: decoder_test.py    License: MIT License 6 votes vote down vote up
def test_decode_time():
    assert _decode_time('03:04:05', True) == time(3, 4, 5, tzinfo=timezone(timedelta(0)))
    # TODO: The standard specifies that the second fraction is limited to one
    # digit, however udatetime only permits 3 or 6 digits.
    assert _decode_time('03:04:05.600', True) == time(3, 4, 5, 600000, tzinfo=timezone(timedelta(0)))
    assert _decode_time('03:04:05Z', True) == time(3, 4, 5, tzinfo=timezone(timedelta(0)))
    assert _decode_time('03:04:05+00:00', True) == time(3, 4, 5, tzinfo=timezone(timedelta(0)))
    assert _decode_time('03:04:05-00:00', True) == time(3, 4, 5, tzinfo=timezone(timedelta(0)))
    assert _decode_time('03:04:05+07:08', True) == time(3, 4, 5, tzinfo=timezone(timedelta(hours=7, minutes=8)))
    assert _decode_time('03:04:05-07:08', True) == time(3, 4, 5, tzinfo=timezone(timedelta(hours=-7, minutes=-8)))
    assert _decode_time('03:04:05.600+07:08', True) == \
           time(3, 4, 5, 600000, tzinfo=timezone(timedelta(hours=7, minutes=8)))
    assert _decode_time('03:04:05', False) == time(3, 4, 5)
    assert _decode_time('03:04:05.600', False) == time(3, 4, 5, 600000)
    assert _decode_time('03:04:05Z', False) == time(3, 4, 5)
    assert _decode_time('03:04:05+00:00', False) == time(3, 4, 5)
    assert _decode_time('03:04:05-00:00', False) == time(3, 4, 5)
    assert _decode_time('12:00:00+07:08', False) == time(4, 52)
    assert _decode_time('12:00:00-07:08', False) == time(19, 8) 
Example 4
Project: compare-codecs   Author: google   File: gviz_api.py    License: Apache License 2.0 6 votes vote down vote up
def default(self, o):
    if isinstance(o, datetime.datetime):
      if o.microsecond == 0:
        # If the time doesn't have ms-resolution, leave it out to keep
        # things smaller.
        return "Date(%d,%d,%d,%d,%d,%d)" % (
            o.year, o.month - 1, o.day, o.hour, o.minute, o.second)
      else:
        return "Date(%d,%d,%d,%d,%d,%d,%d)" % (
            o.year, o.month - 1, o.day, o.hour, o.minute, o.second,
            o.microsecond / 1000)
    elif isinstance(o, datetime.date):
      return "Date(%d,%d,%d)" % (o.year, o.month - 1, o.day)
    elif isinstance(o, datetime.time):
      return [o.hour, o.minute, o.second]
    else:
      return super(DataTableJSONEncoder, self).default(o) 
Example 5
Project: ripozo   Author: vertical-knowledge   File: utilities.py    License: GNU General Public License v2.0 6 votes vote down vote up
def make_json_safe(obj):
    """
    Makes an object json serializable.
    This is designed to take a list or dictionary,
    and is fairly limited.  This is primarily for
    the managers when creating objects.

    :param object obj:
    :return: The json safe dictionary.
    :rtype: object|six.text_type|list|dict
    """
    if isinstance(obj, dict):
        for key, value in six.iteritems(obj):
            obj[key] = make_json_safe(value)
    elif isinstance(obj, (list, set, tuple,)):
        response = []
        for val in obj:
            response.append(make_json_safe(val))
        return response
    elif isinstance(obj, (datetime.datetime, datetime.date, datetime.time, datetime.timedelta)):
        obj = six.text_type(obj)
    elif isinstance(obj, decimal.Decimal):
        obj = float(obj)
    return obj 
Example 6
Project: InsightAgent   Author: insightfinder   File: collectdReportMetrics.py    License: Apache License 2.0 5 votes vote down vote up
def set_from_reporting_config_json():
    # global hostname, hostnameShort
    report_file_name = "reporting_config.json"

    # reading file form reporting_config.json
    with open(os.path.join(home_path, report_file_name), 'r') as f:
        config = json.load(f)

    reporting_interval_string = config['reporting_interval']
    # is_second_reporting = False
    if reporting_interval_string[-1:] == 's':
        # is_second_reporting = True
        reporting_interval_l = float(config['reporting_interval'][:-1])
        reporting_interval_l = float(reporting_interval_l / 60)
    else:
        reporting_interval_l = int(config['reporting_interval'])

    # keep_file_days = int(config['keep_file_days'])
    prev_endtime_l = config['prev_endtime']
    # deltaFields_l = config['delta_fields']

    hostname_l = socket.getfqdn()
    hostname_short_l = socket.gethostname().partition(".")[0]
    csvpath_l = "/var/lib/collectd/csv/" + hostname_short_l

    if not os.path.exists(csvpath_l):
        csvpath_l = "/var/lib/collectd/csv/" + hostname_l
    if not os.path.exists(csvpath_l):
        directory_list = os.listdir("/var/lib/collectd/csv")
        if len(directory_list) > 0:
            csvpath_l = "/var/lib/collectd/csv/" + directory_list[0]

    date_l = time.strftime("%Y-%m-%d")
    return reporting_interval_l, hostname_l, hostname_short_l, prev_endtime_l, csvpath_l, date_l


# deletes old csv files from a directory 
Example 7
Project: InsightAgent   Author: insightfinder   File: collectdReportMetrics.py    License: Apache License 2.0 5 votes vote down vote up
def set_epoch_time(reporting_interval_l, prev_endtime_l):
    if prev_endtime_l != "0":
        start_time = prev_endtime_l
        # pad a second after prev_end_time
        start_time_epoch_l = 1000 + long(1000 * time.mktime(time.strptime(start_time, "%Y%m%d%H%M%S")))
        # end_time_epoch = start_time_epoch_l + 1000 * 60 * reporting_interval_l
        start_time_epoch_l = start_time_epoch_l / 1000
    else:  # prev_endtime == 0
        end_time_epoch = int(time.time()) * 1000
        start_time_epoch_l = end_time_epoch - 1000 * 60 * reporting_interval_l
        start_time_epoch_l = start_time_epoch_l / 1000
    return reporting_interval_l, start_time_epoch_l, prev_endtime_l


# update prev_endtime in config file 
Example 8
Project: InsightAgent   Author: insightfinder   File: collectdReportMetrics.py    License: Apache License 2.0 5 votes vote down vote up
def update_endtime_in_config(metric_data_l, reporting_interval_l, new_prev_endtime_epoch_l, hostname_l):
    if new_prev_endtime_epoch_l == 0:
        print "No data is reported"
    else:
        new_prev_endtimeinsec = math.ceil(long(new_prev_endtime_epoch_l) / 1000.0)
        new_prev_endtime = time.strftime(
            "%Y%m%d%H%M%S", time.localtime(long(new_prev_endtimeinsec)))
        update_timestamp(new_prev_endtime)
        send_data(metric_data_l, reporting_interval_l, hostname_l)
    return 
Example 9
Project: grimoirelab-sortinghat   Author: chaoss   File: grimoirelab.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __force_datetime(self, obj):
        """Converts ojb to time.datetime.datetime

        YAML parsing returns either date or datetime object depending
        on how the date is written. YYYY-MM-DD will return a date and
        YYYY-MM-DDThh:mm:ss will return a datetime

        :param obj: date or datetime object
        """
        if isinstance(obj, datetime.datetime):
            return obj

        t = datetime.time(0, 0)
        return datetime.datetime.combine(obj, t) 
Example 10
Project: pseudo-channel   Author: justinemter   File: PseudoChannel.py    License: GNU General Public License v3.0 5 votes vote down vote up
def time_diff(self, time1,time2):
        '''
        *
        * Getting the offest by comparing both times from the unix epoch time and getting the difference.
        *
        '''
        timeA = datetime.datetime.strptime(time1, '%I:%M:%S %p')
        timeB = datetime.datetime.strptime(time2, '%I:%M:%S %p')
        timeAEpoch = calendar.timegm(timeA.timetuple())
        timeBEpoch = calendar.timegm(timeB.timetuple())
        tdelta = abs(timeAEpoch) - abs(timeBEpoch)
        return int(tdelta/60) 
Example 11
Project: pseudo-channel   Author: justinemter   File: PseudoChannel.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_end_time_from_duration(self, startTime, duration):

        time = datetime.datetime.strptime(startTime, '%I:%M:%S %p')
        show_time_plus_duration = time + datetime.timedelta(milliseconds=duration)
        return show_time_plus_duration 
Example 12
Project: pseudo-channel   Author: justinemter   File: PseudoChannel.py    License: GNU General Public License v3.0 5 votes vote down vote up
def generate_memory_schedule(schedulelist, isforupdate=False):

            print "##### Generating Memory Schedule."
            now = datetime.datetime.now()
            now = now.replace(year=1900, month=1, day=1)
            pseudo_cache = pseudo_channel.get_daily_schedule_cache_as_json()
            prev_end_time_to_watch_for = None
            if pseudo_channel.USE_OVERRIDE_CACHE and isforupdate:
                for cached_item in pseudo_cache:
                    prev_start_time = datetime.datetime.strptime(cached_item[8], "%I:%M:%S %p")
                    try:
                        prev_end_time = datetime.datetime.strptime(cached_item[9], '%Y-%m-%d %H:%M:%S.%f')
                    except ValueError:
                        prev_end_time = datetime.datetime.strptime(cached_item[9], '%Y-%m-%d %H:%M:%S')
                    """If update time is in between the prev media start / stop then there is overlap"""
                    if prev_start_time < now and prev_end_time > now:
                        try:
                            print "+++++ It looks like there is update schedule overlap", cached_item[3]
                        except:
                            pass
                        prev_end_time_to_watch_for = prev_end_time
            for item in schedulelist:
                trans_time = datetime.datetime.strptime(item[8], "%I:%M:%S %p").strftime("%H:%M")
                new_start_time = datetime.datetime.strptime(item[8], "%I:%M:%S %p")
                if prev_end_time_to_watch_for == None:
                    schedule.every().day.at(trans_time).do(job_that_executes_once, item, schedulelist).tag('daily-tasks')
                else:
                    """If prev end time is more then the start time of this media, skip it"""
                    if prev_end_time_to_watch_for > new_start_time:
                        try:
                            print "Skipping scheduling item do to cached overlap.", item[3]
                        except:
                            pass
                        continue
                    else:
                        schedule.every().day.at(trans_time).do(job_that_executes_once, item, schedulelist).tag('daily-tasks')
            print "+++++ Done." 
Example 13
Project: python-esppy   Author: sassoftware   File: base.py    License: Apache License 2.0 5 votes vote down vote up
def to_xml(self, pretty=False, query=None):
        '''
        Export window definition to XML

        Parameters
        ----------
        pretty : bool, optional
            Should the output include whitespace for readability?
        query : ContinuousQuery, optional
            The parent query object of this window

        Examples
        --------
        >>> win.to_xml(pretty=True)
        <window-source insert-only="true" name="w_data">
          <schema>
            <fields>
              <field key="true" name="id" type="int64" />
              <field key="false" name="time" type="double" />
            </fields>
          </schema>
        </window-source>

        Returns
        -------
        string

        '''
        return xml.to_xml(self.to_element(query=query), pretty=pretty) 
Example 14
Project: rets   Author: opendoor-labs   File: decoder.py    License: MIT License 5 votes vote down vote up
def _decode_time(value: str, include_tz: bool) -> time:
    decoded = _decode_datetime('1970-01-01T' + value, include_tz)
    return decoded.time().replace(tzinfo=decoded.tzinfo) 
Example 15
Project: compare-codecs   Author: google   File: gviz_api.py    License: Apache License 2.0 5 votes vote down vote up
def ToString(value):
    if value is None:
      return "(empty)"
    elif isinstance(value, (datetime.datetime,
                            datetime.date,
                            datetime.time)):
      return str(value)
    elif isinstance(value, unicode):
      return value
    elif isinstance(value, bool):
      return str(value).lower()
    else:
      return str(value).decode("utf-8") 
Example 16
Project: ripozo   Author: vertical-knowledge   File: tests_utilities.py    License: GNU General Public License v2.0 5 votes vote down vote up
def test_make_json_safe(self):
        """
        Tests whether the make_json_safe method correctly
        returns values.
        """
        # Test times
        resp = make_json_safe(datetime.datetime.now())
        self.assertIsInstance(resp, six.text_type)
        resp = make_json_safe(datetime.date.today())
        self.assertIsInstance(resp, six.text_type)
        resp = make_json_safe(datetime.time())
        self.assertIsInstance(resp, six.text_type)
        resp = make_json_safe(datetime.timedelta(days=1))
        self.assertIsInstance(resp, six.text_type)

        # Test decimals
        resp = make_json_safe(decimal.Decimal('1.02'))
        self.assertEqual(resp, 1.02)
        self.assertIsInstance(resp, float)

        # Test lists
        l = [datetime.time(), datetime.date.today(), datetime.datetime.now()]
        resp = make_json_safe(l)
        self.assertIsInstance(resp, list)
        for item in resp:
            self.assertIsInstance(item, six.text_type)

        # Test dictionary
        d = dict(a=datetime.datetime.now(), b=datetime.time(), c=datetime.date.today())
        resp = make_json_safe(d)
        self.assertIsInstance(resp, dict)
        for key, value in six.iteritems(resp):
            self.assertIsInstance(value, six.text_type) 
Example 17
Project: asn1tools   Author: eerimoq   File: xer.py    License: MIT License 5 votes vote down vote up
def decode(self, element):
        return datetime.date(*time.strptime(element.text, '%Y-%m-%d')[:3]) 
Example 18
Project: asn1tools   Author: eerimoq   File: xer.py    License: MIT License 5 votes vote down vote up
def decode(self, element):
        return datetime.time(*time.strptime(element.text, '%H:%M:%S')[3:6]) 
Example 19
Project: asn1tools   Author: eerimoq   File: xer.py    License: MIT License 5 votes vote down vote up
def decode(self, element):
        return datetime.datetime(*time.strptime(element.text,
                                                '%Y-%m-%dT%H:%M:%S')[:6]) 
Example 20
Project: asn1tools   Author: eerimoq   File: jer.py    License: MIT License 5 votes vote down vote up
def decode(self, data):
        return datetime.date(*time.strptime(data, '%Y-%m-%d')[:3]) 
Example 21
Project: asn1tools   Author: eerimoq   File: jer.py    License: MIT License 5 votes vote down vote up
def decode(self, data):
        return datetime.time(*time.strptime(data, '%H:%M:%S')[3:6]) 
Example 22
Project: asn1tools   Author: eerimoq   File: per.py    License: MIT License 5 votes vote down vote up
def decode(self, decoder):
        decoded = self._inner.decode(decoder)

        return datetime.time(decoded['hours'],
                             decoded['minutes'],
                             decoded['seconds']) 
Example 23
Project: asn1tools   Author: eerimoq   File: per.py    License: MIT License 5 votes vote down vote up
def __init__(self, name):
        super(DateTime, self).__init__(name, 'DATE-TIME')
        self._inner = Sequence('DATE-TIME-ENCODING',
                               [Date('date'), TimeOfDay('time')],
                               None) 
Example 24
Project: asn1tools   Author: eerimoq   File: per.py    License: MIT License 5 votes vote down vote up
def encode(self, data, encoder):
        data = {
            'date': data,
            'time': data
        }

        return self._inner.encode(data, encoder) 
Example 25
Project: asn1tools   Author: eerimoq   File: per.py    License: MIT License 5 votes vote down vote up
def decode(self, decoder):
        decoded = self._inner.decode(decoder)

        return datetime.datetime(decoded['date'].year,
                                 decoded['date'].month,
                                 decoded['date'].day,
                                 decoded['time'].hour,
                                 decoded['time'].minute,
                                 decoded['time'].second) 
Example 26
Project: asn1tools   Author: eerimoq   File: type_checker.py    License: MIT License 5 votes vote down vote up
def encode(self, data):
        if not isinstance(data, datetime.time):
            raise EncodeError(
                'Expected data of type datetime.time, but got {}.'.format(
                    data)) 
Example 27
Project: asn1tools   Author: eerimoq   File: ber.py    License: MIT License 5 votes vote down vote up
def decode(self, data, offset):
        offset = self.decode_tag(data, offset)
        length, offset = decode_length_definite(data, offset)
        end_offset = offset + length
        decoded = data[offset:end_offset].decode('ascii')
        decoded = datetime.date(*time.strptime(decoded, '%Y%m%d')[:3])

        return decoded, end_offset 
Example 28
Project: asn1tools   Author: eerimoq   File: ber.py    License: MIT License 5 votes vote down vote up
def decode(self, data, offset):
        offset = self.decode_tag(data, offset)
        length, offset = decode_length_definite(data, offset)
        end_offset = offset + length
        decoded = data[offset:end_offset].decode('ascii')
        decoded = datetime.time(*time.strptime(decoded, '%H%M%S')[3:6])

        return decoded, end_offset 
Example 29
Project: asn1tools   Author: eerimoq   File: ber.py    License: MIT License 5 votes vote down vote up
def decode(self, data, offset):
        offset = self.decode_tag(data, offset)
        length, offset = decode_length_definite(data, offset)
        end_offset = offset + length
        decoded = data[offset:end_offset].decode('ascii')
        decoded = datetime.datetime(*time.strptime(decoded, '%Y%m%d%H%M%S')[:6])

        return decoded, end_offset 
Example 30
Project: asn1tools   Author: eerimoq   File: oer.py    License: MIT License 5 votes vote down vote up
def decode(self, decoder):
        decoded = self._inner.decode(decoder)

        return datetime.time(decoded['hours'],
                             decoded['minutes'],
                             decoded['seconds'])