Python datetime.time() Examples

The following are 30 code examples of datetime.time(). 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 also want to check out all available functions/classes of the module datetime , or try the search function .
Example #1
Source File: main.py    From kw_condition with 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
Source File: utilities.py    From ripozo with 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 #3
Source File: gviz_api.py    From compare-codecs with 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 #4
Source File: decoder.py    From rets with MIT License 6 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 #5
Source File: decoder_test.py    From rets with 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 #6
Source File: collectdReportMetrics.py    From InsightAgent with 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 #7
Source File: type_detection.py    From sato with Apache License 2.0 5 votes vote down vote up
def detect_time(e):
    if isinstance(e, datetime.time):
        return True
    return False 
Example #8
Source File: test_tz.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def testTimeOnlyOffsetLocalUTC(self):
        with TZEnvContext(self.UTC):
            self.assertEqual(dt_time(13, 20, tzinfo=tz.tzlocal()).utcoffset(),
                             timedelta(0)) 
Example #9
Source File: peewee.py    From Quiver-alfred with MIT License 5 votes vote down vote up
def python_value(self, value):
        if value:
            if isinstance(value, basestring):
                pp = lambda x: x.time()
                return format_date_time(value, self.formats, pp)
            elif isinstance(value, datetime.datetime):
                return value.time()
        if value is not None and isinstance(value, datetime.timedelta):
            return (datetime.datetime.min + value).time()
        return value 
Example #10
Source File: test_tz.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def testTimeOnlyDSTLocalDST(self):
        with TZEnvContext(self.TZ_EST):
            self.assertIs(dt_time(13, 20, tzinfo=tz.tzlocal()).dst(),
                          None) 
Example #11
Source File: dataset.py    From Quiver-alfred with MIT License 5 votes vote down vote up
def default(o):
        if isinstance(o, (datetime.datetime, datetime.date, datetime.time)):
            return o.isoformat()
        elif isinstance(o, Decimal):
            return str(o)
        raise TypeError('Unable to serialize %r as JSON.' % o) 
Example #12
Source File: utils.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def today(tzinfo=None):
    """
    Returns a :py:class:`datetime` representing the current day at midnight

    :param tzinfo:
        The time zone to attach (also used to determine the current day).

    :return:
        A :py:class:`datetime.datetime` object representing the current day
        at midnight.
    """

    dt = datetime.now(tzinfo)
    return datetime.combine(dt.date(), time(0, tzinfo=tzinfo)) 
Example #13
Source File: rrule.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def stimeset(self, hour, minute, second):
        return (datetime.time(hour, minute, second,
                tzinfo=self.rrule._tzinfo),) 
Example #14
Source File: isoparser.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, sep=None):
        """
        :param sep:
            A single character that separates date and time portions. If
            ``None``, the parser will accept any single character.
            For strict ISO-8601 adherence, pass ``'T'``.
        """
        if sep is not None:
            if (len(sep) != 1 or ord(sep) >= 128 or sep in '0123456789'):
                raise ValueError('Separator must be a single, non-numeric ' +
                                 'ASCII character')

            sep = sep.encode('ascii')

        self._sep = sep 
Example #15
Source File: isoparser.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def parse_isotime(self, timestr):
        """
        Parse the time portion of an ISO string.

        :param timestr:
            The time portion of an ISO string, without a separator

        :return:
            Returns a :class:`datetime.time` object
        """
        return time(*self._parse_isotime(timestr)) 
Example #16
Source File: isoparser.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def _parse_tzstr(self, tzstr, zero_as_utc=True):
        if tzstr == b'Z':
            return tz.tzutc()

        if len(tzstr) not in {3, 5, 6}:
            raise ValueError('Time zone offset must be 1, 3, 5 or 6 characters')

        if tzstr[0:1] == b'-':
            mult = -1
        elif tzstr[0:1] == b'+':
            mult = 1
        else:
            raise ValueError('Time zone offset requires sign')

        hours = int(tzstr[1:3])
        if len(tzstr) == 3:
            minutes = 0
        else:
            minutes = int(tzstr[(4 if tzstr[3:4] == self._TIME_SEP else 3):])

        if zero_as_utc and hours == 0 and minutes == 0:
            return tz.tzutc()
        else:
            if minutes > 59:
                raise ValueError('Invalid minutes in time zone offset')

            if hours > 23:
                raise ValueError('Invalid hours in time zone offset')

            return tz.tzoffset(None, mult * (hours * 60 + minutes) * 60) 
Example #17
Source File: test_tz.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def testTimeOnlyUTC(self):
        # https://github.com/dateutil/dateutil/issues/132
        # tzutc doesn't care
        tz_utc = tz.tzutc()
        self.assertEqual(dt_time(13, 20, tzinfo=tz_utc).utcoffset(),
                         timedelta(0)) 
Example #18
Source File: converter.py    From snowflake-connector-python with Apache License 2.0 5 votes vote down vote up
def _TIME_to_python(self, ctx):
        """TIME to formatted string, SnowflakeDateTime, or datetime.time with no timezone attached."""
        scale = ctx['scale']

        conv0 = lambda value: datetime.utcfromtimestamp(float(value)).time()

        def conv(value: str) -> dt_t:
            microseconds = float(value[0:-scale + 6])
            return datetime.utcfromtimestamp(microseconds).time()

        return conv if scale > 6 else conv0 
Example #19
Source File: dbapi.py    From snowflake-connector-python with Apache License 2.0 5 votes vote down vote up
def TimestampFromTicks(ticks):
    return Timestamp(*time.localtime(ticks)[:6]) 
Example #20
Source File: dbapi.py    From snowflake-connector-python with Apache License 2.0 5 votes vote down vote up
def TimeFromTicks(ticks):
    return Time(*time.localtime(ticks)[3:6]) 
Example #21
Source File: dbapi.py    From snowflake-connector-python with Apache License 2.0 5 votes vote down vote up
def DateFromTicks(ticks):
    return Date(*time.localtime(ticks)[:3]) 
Example #22
Source File: randgen.py    From donation-tracker with Apache License 2.0 5 votes vote down vote up
def build_random_event(
    rand,
    *,
    start_time=None,
    num_donors=0,
    num_donations=0,
    num_runs=0,
    num_bids=0,
    num_prizes=0,
):
    if not PrizeCategory.objects.all().exists() and num_prizes > 0:
        PrizeCategory.objects.create(name='Game')
        PrizeCategory.objects.create(name='Grand')
        PrizeCategory.objects.create(name='Grab Bag')

    event = generate_event(rand, start_time=start_time)
    if not start_time:
        start_time = datetime.datetime.combine(event.date, datetime.time()).replace(
            tzinfo=pytz.utc
        )
    event.save()

    list_of_runs = generate_runs(rand, event=event, num_runs=num_runs, scheduled=True)
    last_run_time = list_of_runs[-1].endtime if list_of_runs else start_time
    list_of_donors = generate_donors(rand, num_donors=num_donors)
    top_bids_list, bid_targets_list = generate_bids(
        rand, event=event, num_bids=num_bids, list_of_runs=list_of_runs
    )
    generate_prizes(rand, event=event, num_prizes=num_prizes, list_of_runs=list_of_runs)
    generate_donations(
        rand,
        event=event,
        num_donations=num_donations,
        start_time=start_time,
        end_time=last_run_time,
        donors=list_of_donors,
        assign_bids=True,
        bid_targets_list=bid_targets_list,
    )

    return event 
Example #23
Source File: 0003_backfill_event_datetime.py    From donation-tracker with Apache License 2.0 5 votes vote down vote up
def backfill_event_datetime(apps, schema_editor):
    # noinspection PyPep8Naming
    Event = apps.get_model('tracker', 'Event')
    db_alias = schema_editor.connection.alias
    for event in Event.objects.using(db_alias).order_by('date'):
        run = event.speedrun_set.order_by('starttime').first()
        print(event.name)
        if run and run.starttime:
            event.datetime = run.starttime
            print('run start %s' % event.datetime.astimezone(event.timezone))
        else:
            event.datetime = event.timezone.localize(datetime.datetime.combine(event.date, datetime.time(12, 0)))
            print('noon default')
        event.save() 
Example #24
Source File: test_api.py    From tomlkit with MIT License 5 votes vote down vote up
def test_datetime():
    dt = tomlkit.datetime("1979-05-13T12:34:56")

    assert isinstance(dt, DateTime)

    with pytest.raises(ValueError):
        tomlkit.time("1979-05-13") 
Example #25
Source File: test_api.py    From tomlkit with MIT License 5 votes vote down vote up
def test_time():
    dt = tomlkit.time("12:34:56")

    assert isinstance(dt, Time)

    with pytest.raises(ValueError):
        tomlkit.time("1979-05-13") 
Example #26
Source File: test_api.py    From tomlkit with MIT License 5 votes vote down vote up
def json_serial(obj):
    """JSON serializer for objects not serializable by default json code"""
    if isinstance(obj, (datetime, date, time)):
        return obj.isoformat()

    raise TypeError("Type {} not serializable".format(type(obj))) 
Example #27
Source File: api.py    From tomlkit with MIT License 5 votes vote down vote up
def time(raw):  # type: (str) -> Time
    value = parse_rfc3339(raw)
    if not isinstance(value, _datetime.time):
        raise ValueError("time() only accepts time strings.")

    return item(value) 
Example #28
Source File: test_codecs_consistency.py    From asn1tools with MIT License 5 votes vote down vote up
def test_time_of_day(self):
        decoded = time(15, 27, 46)

        encoded = [
            b'\x1f\x20\x06\x31\x35\x32\x37\x34\x36',
            b'\x1f\x20\x06\x31\x35\x32\x37\x34\x36',
            b'"15:27:46"',
            b'\x0f\x1b\x2e',
            b'\x7b\x77\x00',
            b'\x7b\x77\x00',
            b'<A>15:27:46</A>',
            b'a A ::= "15:27:46"'
        ]

        self.encode_decode_codecs('TIME-OF-DAY', decoded, encoded) 
Example #29
Source File: test_tz.py    From plugin.video.emby with GNU General Public License v3.0 5 votes vote down vote up
def testTimeOnlyGettz(self):
        # gettz returns None
        tz_get = self.gettz('Europe/Minsk')
        self.assertIs(dt_time(13, 20, tzinfo=tz_get).utcoffset(), None) 
Example #30
Source File: converters.py    From ServerlessCrawler-VancouverRealState with MIT License 5 votes vote down vote up
def convert_time(obj):
    """Returns a TIME column as a time object:

      >>> time_or_None('15:06:17')
      datetime.time(15, 6, 17)

    Illegal values are returned as None:

      >>> time_or_None('-25:06:17') is None
      True
      >>> time_or_None('random crap') is None
      True

    Note that MySQL always returns TIME columns as (+|-)HH:MM:SS, but
    can accept values as (+|-)DD HH:MM:SS. The latter format will not
    be parsed correctly by this function.

    Also note that MySQL's TIME column corresponds more closely to
    Python's timedelta and not time. However if you want TIME columns
    to be treated as time-of-day and not a time offset, then you can
    use set this function as the converter for FIELD_TYPE.TIME.
    """
    if not PY2 and isinstance(obj, (bytes, bytearray)):
        obj = obj.decode('ascii')

    m = TIME_RE.match(obj)
    if not m:
        return None

    try:
        groups = list(m.groups())
        groups[-1] = _convert_second_fraction(groups[-1])
        hours, minutes, seconds, microseconds = groups
        return datetime.time(hour=int(hours), minute=int(minutes),
                             second=int(seconds), microsecond=int(microseconds))
    except ValueError:
        return None