Python datetime.time() Examples

The following are code examples for showing how to use datetime.time(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: util.py    MIT License 7 votes vote down vote up
def isoformat(self, sep='T'):
        """
        Formats the date as "%Y-%m-%d %H:%M:%S" with the sep param between the
        date and time portions

        :param set:
            A single character of the separator to place between the date and
            time

        :return:
            The formatted datetime as a unicode string in Python 3 and a byte
            string in Python 2
        """

        if self.microsecond == 0:
            return self.strftime('0000-%%m-%%d%s%%H:%%M:%%S' % sep)
        return self.strftime('0000-%%m-%%d%s%%H:%%M:%%S.%%f' % sep) 
Example 2
Project: flasky   Author: RoseOu   File: base.py    MIT License 6 votes vote down vote up
def result_processor(self, dialect, coltype):
        time = datetime.time

        def process(value):
            # convert from a timedelta value
            if value is not None:
                microseconds = value.microseconds
                seconds = value.seconds
                minutes = seconds // 60
                return time(minutes // 60,
                            minutes % 60,
                            seconds - minutes * 60,
                            microsecond=microseconds)
            else:
                return None
        return process 
Example 3
Project: flasky   Author: RoseOu   File: base.py    MIT License 6 votes vote down vote up
def bind_processor(self, dialect):
        datetime_time = datetime.time
        format = self._storage_format

        def process(value):
            if value is None:
                return None
            elif isinstance(value, datetime_time):
                return format % {
                    'hour': value.hour,
                    'minute': value.minute,
                    'second': value.second,
                    'microsecond': value.microsecond,
                }
            else:
                raise TypeError("SQLite Time type only accepts Python "
                                "time objects as input.")
        return process 
Example 4
Project: flasky   Author: RoseOu   File: base.py    MIT License 6 votes vote down vote up
def __init__(self, isolation_level=None, native_datetime=False, **kwargs):
        default.DefaultDialect.__init__(self, **kwargs)
        self.isolation_level = isolation_level

        # this flag used by pysqlite dialect, and perhaps others in the
        # future, to indicate the driver is handling date/timestamp
        # conversions (and perhaps datetime/time as well on some hypothetical
        # driver ?)
        self.native_datetime = native_datetime

        if self.dbapi is not None:
            self.supports_default_values = (
                self.dbapi.sqlite_version_info >= (3, 3, 8))
            self.supports_cast = (
                self.dbapi.sqlite_version_info >= (3, 2, 3))
            self.supports_multivalues_insert = (
                # http://www.sqlite.org/releaselog/3_7_11.html
                self.dbapi.sqlite_version_info >= (3, 7, 11))
            # see http://www.sqlalchemy.org/trac/ticket/2568
            # as well as http://www.sqlite.org/src/info/600482d161
            self._broken_fk_pragma_quotes = (
                self.dbapi.sqlite_version_info < (3, 6, 14)) 
Example 5
Project: kw_condition   Author: coreanq   File: main.py    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 6
Project: bigquerylayers   Author: smandaric   File: datetime_helpers.py    GNU General Public License v3.0 6 votes vote down vote up
def to_rfc3339(value, ignore_zone=True):
    """Convert a datetime to an RFC3339 timestamp string.

    Args:
        value (datetime.datetime):
            The datetime object to be converted to a string.
        ignore_zone (bool): If True, then the timezone (if any) of the
            datetime object is ignored and the datetime is treated as UTC.

    Returns:
        str: The RFC3339 formated string representing the datetime.
    """
    if not ignore_zone and value.tzinfo is not None:
        # Convert to UTC and remove the time zone info.
        value = value.replace(tzinfo=None) - value.utcoffset()

    return value.strftime(_RFC3339_MICROS) 
Example 7
Project: bigquerylayers   Author: smandaric   File: types.py    GNU General Public License v3.0 6 votes vote down vote up
def TimeFromTicks(ticks, tz=None):
    """Construct a DB-API time value from the given ticks value.

    :type ticks: float
    :param ticks:
        a number of seconds since the epoch; see the documentation of the
        standard Python time module for details.

    :type tz: :class:`datetime.tzinfo`
    :param tz: (Optional) time zone to use for conversion

    :rtype: :class:`datetime.time`
    :returns: time represented by ticks.
    """
    dt = datetime.datetime.fromtimestamp(ticks, tz=tz)
    return dt.timetz() 
Example 8
Project: bigquerylayers   Author: smandaric   File: _helpers.py    GNU General Public License v3.0 6 votes vote down vote up
def _time_from_iso8601_time_naive(value):
    """Convert a zoneless ISO8601 time string to naive datetime time

    :type value: str
    :param value: The time string to convert

    :rtype: :class:`datetime.time`
    :returns: A datetime time object created from the string
    :raises ValueError: if the value does not match a known format.
    """
    if len(value) == 8:  # HH:MM:SS
        fmt = _TIMEONLY_NO_FRACTION
    elif len(value) == 15:  # HH:MM:SS.micros
        fmt = _TIMEONLY_W_MICROS
    else:
        raise ValueError("Unknown time format: {}".format(value))
    return datetime.datetime.strptime(value, fmt).time() 
Example 9
Project: bigquerylayers   Author: smandaric   File: _helpers.py    GNU General Public License v3.0 6 votes vote down vote up
def _datetime_to_rfc3339(value, ignore_zone=True):
    """Convert a timestamp to a string.

    :type value: :class:`datetime.datetime`
    :param value: The datetime object to be converted to a string.

    :type ignore_zone: bool
    :param ignore_zone: If True, then the timezone (if any) of the datetime
                        object is ignored.

    :rtype: str
    :returns: The string representing the datetime stamp.
    """
    if not ignore_zone and value.tzinfo is not None:
        # Convert to UTC and remove the time zone info.
        value = value.replace(tzinfo=None) - value.utcoffset()

    return value.strftime(_RFC3339_MICROS) 
Example 10
Project: InsightAgent   Author: insightfinder   File: collectdReportMetrics.py    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 11
Project: pytracts   Author: rmorlok   File: to_json.py    Apache License 2.0 6 votes vote down vote up
def prep_dict(self, d):
        """
        Prepare a dictionary for encoding by making sure non-json serializable types that
        we know how to handle are converted.

        :param d: the dict

        :return: the updated dict
        """
        if d is None:
            return None

        d = d.copy()

        for key in d.iterkeys():
            if isinstance(d[key], datetime.datetime) or isinstance(d[key], datetime.date) or isinstance(d[key], datetime.time):
                d[key] = d[key].isoformat()
            if isinstance(d[key], dict):
                d[key] = self.prep_dict(d[key])

        return d 
Example 12
Project: rowgenerators   Author: Metatab   File: core.py    MIT License 6 votes vote down vote up
def __new__(cls, v):
        from dateutil import parser

        if v is None or (isinstance(v, str) and v.strip() == ''):
            return NoneValue

        try:
            if isinstance(v, time):
                d = v
            elif not isinstance(v, str):
                d = parser.parse(str(v))
            else:
                d = parser.parse(v)

            return super(TimeValue, cls).__new__(cls, d.hour, d.minute, d.second)
        except TypeError:
            if str(v) == 'NaT':  # THe Pandas "Not A Time" value
                return NoneValue
            raise 
Example 13
Project: rowgenerators   Author: Metatab   File: types.py    MIT License 6 votes vote down vote up
def parse_time(v, header_d):
    from rowgenerators.rowpipe.exceptions import CastingError

    v = nullify(v)

    if v is None:
        return None

    if isinstance(v, str):
        try:
            return dp.parse(v).time()
        except ValueError as e:
            raise CastingError(datetime.time, header_d, v, str(e))

    elif isinstance(v, datetime.time):
        return v
    else:
        raise CastingError(int, header_d, v, "Expected datetime.time or basestring, got '{}'".format(type(v))) 
Example 14
Project: rowgenerators   Author: Metatab   File: types.py    MIT License 6 votes vote down vote up
def parse_datetime(v, header_d):
    from rowgenerators.rowpipe.exceptions import CastingError

    v = nullify(v)

    if v is None:
        return None

    if isinstance(v, str):
        try:
            return dp.parse(v)
        except (ValueError, TypeError) as e:
            raise CastingError(datetime.datetim, header_d, v, str(e))

    elif isinstance(v, datetime.datetime):
        return v
    else:
        raise CastingError(int, header_d, v, "Expected datetime.time or basestring, got '{}'".format(type(v))) 
Example 15
Project: where   Author: kartverket   File: gnss_bias.py    MIT License 6 votes vote down vote up
def get_dsb(self, satellite, dsb, given_date):
        """Get correct Differential Signal Bias for given satellite, DSB code and date

        Args:
            satellite (str):              Satellite identifier.
            dsb (str):                    Differential Signal Bias combination (e.g. 'C1C-C1W')
            given_date (datetime.date):   Given date used for finding corresponding time period in GNSS bias file
        """
        used_date = None
        # TODO: Would it be not better to define rundate as datetime.datetime instead datetime.date?
        given_date = datetime.datetime.combine(given_date, datetime.time())  # conversion from date to datetime

        for date in sorted(self.data[satellite][dsb]):
            if date <= given_date:
                used_date = date

        if (used_date is None) or (given_date > self.data[satellite][dsb][used_date]["end_time"]):
            log.warn(
                "No satellite GNSS bias is given for satellite {}, Differential Signal Bias (DSB) {} and time {}. ",
                satellite,
                dsb,
                given_date,
            )

        return self.data[satellite][dsb][used_date] 
Example 16
Project: openhatch   Author: campbe13   File: serialize.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def default(self, o):
        if isinstance(o, datetime.datetime):
            return o.strftime("%s %s" % (self.DATE_FORMAT, self.TIME_FORMAT))
        elif isinstance(o, datetime.date):
            return o.strftime(self.DATE_FORMAT)
        elif isinstance(o, datetime.time):
            return o.strftime(self.TIME_FORMAT)
        elif isinstance(o, decimal.Decimal):
            return str(o)
        elif isinstance(o, defer.Deferred):
            return str(o)
        elif isinstance(o, Request):
            return "<%s %s %s>" % (type(o).__name__, o.method, o.url)
        elif isinstance(o, Response):
            return "<%s %s %s>" % (type(o).__name__, o.status, o.url)
        else:
            return super(ScrapyJSONEncoder, self).default(o) 
Example 17
Project: deb-python-cassandra-driver   Author: openstack   File: util.py    Apache License 2.0 6 votes vote down vote up
def __init__(self, value):
        """
        Initializer value can be:

            - integer_type: absolute nanoseconds in the day
            - datetime.time: built-in time
            - string_type: a string time of the form "HH:MM:SS[.mmmuuunnn]"
        """
        if isinstance(value, six.integer_types):
            self._from_timestamp(value)
        elif isinstance(value, datetime.time):
            self._from_time(value)
        elif isinstance(value, six.string_types):
            self._from_timestring(value)
        else:
            raise TypeError('Time arguments must be a whole number, datetime.time, or string') 
Example 18
Project: deb-python-cassandra-driver   Author: openstack   File: util.py    Apache License 2.0 6 votes vote down vote up
def __init__(self, value):
        """
        Initializer value can be:

            - integer_type: absolute days from epoch (1970, 1, 1). Can be negative.
            - datetime.date: built-in date
            - string_type: a string time of the form "yyyy-mm-dd"
        """
        if isinstance(value, six.integer_types):
            self.days_from_epoch = value
        elif isinstance(value, (datetime.date, datetime.datetime)):
            self._from_timetuple(value.timetuple())
        elif isinstance(value, six.string_types):
            self._from_datestring(value)
        else:
            raise TypeError('Date arguments must be a whole number, datetime.date, or string') 
Example 19
Project: pyblish-win   Author: pyblish   File: dbapi2.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def DateFromTicks(ticks):
    return Date(*time.localtime(ticks)[:3]) 
Example 20
Project: pyblish-win   Author: pyblish   File: dbapi2.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def TimeFromTicks(ticks):
    return Time(*time.localtime(ticks)[3:6]) 
Example 21
Project: pyblish-win   Author: pyblish   File: dbapi2.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def TimestampFromTicks(ticks):
    return Timestamp(*time.localtime(ticks)[:6]) 
Example 22
Project: xadmin_bugfix   Author: vip68   File: util.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def display_for_value(value, boolean=False):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if boolean:
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(value, datetime.datetime):
        return formats.localize(tz_localtime(value))
    elif isinstance(value, (datetime.date, datetime.time)):
        return formats.localize(value)
    elif isinstance(value, (decimal.Decimal, float)):
        return formats.number_format(value)
    else:
        return smart_text(value) 
Example 23
Project: xadmin_bugfix   Author: vip68   File: export.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_xlsx_export(self, context):
        datas = self._get_datas(context)
        output = io.BytesIO()
        export_header = (
            self.request.GET.get('export_xlsx_header', 'off') == 'on')

        model_name = self.opts.verbose_name
        book = xlsxwriter.Workbook(output)
        sheet = book.add_worksheet(
            u"%s %s" % (_(u'Sheet'), force_text(model_name)))
        styles = {'datetime': book.add_format({'num_format': 'yyyy-mm-dd hh:mm:ss'}),
                  'date': book.add_format({'num_format': 'yyyy-mm-dd'}),
                  'time': book.add_format({'num_format': 'hh:mm:ss'}),
                  'header': book.add_format({'font': 'name Times New Roman', 'color': 'red', 'bold': 'on', 'num_format': '#,##0.00'}),
                  'default': book.add_format()}

        if not export_header:
            datas = datas[1:]
        for rowx, row in enumerate(datas):
            for colx, value in enumerate(row):
                if export_header and rowx == 0:
                    cell_style = styles['header']
                else:
                    if isinstance(value, datetime.datetime):
                        cell_style = styles['datetime']
                    elif isinstance(value, datetime.date):
                        cell_style = styles['date']
                    elif isinstance(value, datetime.time):
                        cell_style = styles['time']
                    else:
                        cell_style = styles['default']
                sheet.write(rowx, colx, value, cell_style)
        book.close()

        output.seek(0)
        return output.getvalue() 
Example 24
Project: xadmin_bugfix   Author: vip68   File: export.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_xls_export(self, context):
        datas = self._get_datas(context)
        output = io.BytesIO()
        export_header = (
            self.request.GET.get('export_xls_header', 'off') == 'on')

        model_name = self.opts.verbose_name
        book = xlwt.Workbook(encoding='utf8')
        sheet = book.add_sheet(
            u"%s %s" % (_(u'Sheet'), force_text(model_name)))
        styles = {'datetime': xlwt.easyxf(num_format_str='yyyy-mm-dd hh:mm:ss'),
                  'date': xlwt.easyxf(num_format_str='yyyy-mm-dd'),
                  'time': xlwt.easyxf(num_format_str='hh:mm:ss'),
                  'header': xlwt.easyxf('font: name Times New Roman, color-index red, bold on', num_format_str='#,##0.00'),
                  'default': xlwt.Style.default_style}

        if not export_header:
            datas = datas[1:]
        for rowx, row in enumerate(datas):
            for colx, value in enumerate(row):
                if export_header and rowx == 0:
                    cell_style = styles['header']
                else:
                    if isinstance(value, datetime.datetime):
                        cell_style = styles['datetime']
                    elif isinstance(value, datetime.date):
                        cell_style = styles['date']
                    elif isinstance(value, datetime.time):
                        cell_style = styles['time']
                    else:
                        cell_style = styles['default']
                sheet.write(rowx, colx, value, style=cell_style)
        book.save(output)

        output.seek(0)
        return output.getvalue() 
Example 25
Project: django-xadmin   Author: MarkHoo   File: util.py    MIT License 5 votes vote down vote up
def display_for_value(value, boolean=False):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if boolean:
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(value, datetime.datetime):
        return formats.localize(tz_localtime(value))
    elif isinstance(value, (datetime.date, datetime.time)):
        return formats.localize(value)
    elif isinstance(value, (decimal.Decimal, float)):
        return formats.number_format(value)
    else:
        return smart_text(value) 
Example 26
Project: django-xadmin   Author: MarkHoo   File: export.py    MIT License 5 votes vote down vote up
def get_xlsx_export(self, context):
        datas = self._get_datas(context)
        output = io.BytesIO()
        export_header = (
            self.request.GET.get('export_xlsx_header', 'off') == 'on')

        model_name = self.opts.verbose_name
        book = xlsxwriter.Workbook(output)
        sheet = book.add_worksheet(
            u"%s %s" % (_(u'Sheet'), force_text(model_name)))
        styles = {'datetime': book.add_format({'num_format': 'yyyy-mm-dd hh:mm:ss'}),
                  'date': book.add_format({'num_format': 'yyyy-mm-dd'}),
                  'time': book.add_format({'num_format': 'hh:mm:ss'}),
                  'header': book.add_format({'font': 'name Times New Roman', 'color': 'red', 'bold': 'on', 'num_format': '#,##0.00'}),
                  'default': book.add_format()}

        if not export_header:
            datas = datas[1:]
        for rowx, row in enumerate(datas):
            for colx, value in enumerate(row):
                if export_header and rowx == 0:
                    cell_style = styles['header']
                else:
                    if isinstance(value, datetime.datetime):
                        cell_style = styles['datetime']
                    elif isinstance(value, datetime.date):
                        cell_style = styles['date']
                    elif isinstance(value, datetime.time):
                        cell_style = styles['time']
                    else:
                        cell_style = styles['default']
                sheet.write(rowx, colx, value, cell_style)
        book.close()

        output.seek(0)
        return output.getvalue() 
Example 27
Project: django-xadmin   Author: MarkHoo   File: export.py    MIT License 5 votes vote down vote up
def get_xls_export(self, context):
        datas = self._get_datas(context)
        output = io.BytesIO()
        export_header = (
            self.request.GET.get('export_xls_header', 'off') == 'on')

        model_name = self.opts.verbose_name
        book = xlwt.Workbook(encoding='utf8')
        sheet = book.add_sheet(
            u"%s %s" % (_(u'Sheet'), force_text(model_name)))
        styles = {'datetime': xlwt.easyxf(num_format_str='yyyy-mm-dd hh:mm:ss'),
                  'date': xlwt.easyxf(num_format_str='yyyy-mm-dd'),
                  'time': xlwt.easyxf(num_format_str='hh:mm:ss'),
                  'header': xlwt.easyxf('font: name Times New Roman, color-index red, bold on', num_format_str='#,##0.00'),
                  'default': xlwt.Style.default_style}

        if not export_header:
            datas = datas[1:]
        for rowx, row in enumerate(datas):
            for colx, value in enumerate(row):
                if export_header and rowx == 0:
                    cell_style = styles['header']
                else:
                    if isinstance(value, datetime.datetime):
                        cell_style = styles['datetime']
                    elif isinstance(value, datetime.date):
                        cell_style = styles['date']
                    elif isinstance(value, datetime.time):
                        cell_style = styles['time']
                    else:
                        cell_style = styles['default']
                sheet.write(rowx, colx, value, style=cell_style)
        book.save(output)

        output.seek(0)
        return output.getvalue() 
Example 28
Project: django-xadmin   Author: MarkHoo   File: util.py    MIT License 5 votes vote down vote up
def display_for_value(value, boolean=False):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if boolean:
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(value, datetime.datetime):
        return formats.localize(tz_localtime(value))
    elif isinstance(value, (datetime.date, datetime.time)):
        return formats.localize(value)
    elif isinstance(value, (decimal.Decimal, float)):
        return formats.number_format(value)
    else:
        return smart_text(value) 
Example 29
Project: django-xadmin   Author: MarkHoo   File: export.py    MIT License 5 votes vote down vote up
def get_xlsx_export(self, context):
        datas = self._get_datas(context)
        output = io.BytesIO()
        export_header = (
            self.request.GET.get('export_xlsx_header', 'off') == 'on')

        model_name = self.opts.verbose_name
        book = xlsxwriter.Workbook(output)
        sheet = book.add_worksheet(
            u"%s %s" % (_(u'Sheet'), force_text(model_name)))
        styles = {'datetime': book.add_format({'num_format': 'yyyy-mm-dd hh:mm:ss'}),
                  'date': book.add_format({'num_format': 'yyyy-mm-dd'}),
                  'time': book.add_format({'num_format': 'hh:mm:ss'}),
                  'header': book.add_format({'font': 'name Times New Roman', 'color': 'red', 'bold': 'on', 'num_format': '#,##0.00'}),
                  'default': book.add_format()}

        if not export_header:
            datas = datas[1:]
        for rowx, row in enumerate(datas):
            for colx, value in enumerate(row):
                if export_header and rowx == 0:
                    cell_style = styles['header']
                else:
                    if isinstance(value, datetime.datetime):
                        cell_style = styles['datetime']
                    elif isinstance(value, datetime.date):
                        cell_style = styles['date']
                    elif isinstance(value, datetime.time):
                        cell_style = styles['time']
                    else:
                        cell_style = styles['default']
                sheet.write(rowx, colx, value, cell_style)
        book.close()

        output.seek(0)
        return output.getvalue() 
Example 30
Project: django-xadmin   Author: MarkHoo   File: util.py    MIT License 5 votes vote down vote up
def display_for_value(value, boolean=False):
    from xadmin.views.list import EMPTY_CHANGELIST_VALUE

    if boolean:
        return boolean_icon(value)
    elif value is None:
        return EMPTY_CHANGELIST_VALUE
    elif isinstance(value, datetime.datetime):
        return formats.localize(tz_localtime(value))
    elif isinstance(value, (datetime.date, datetime.time)):
        return formats.localize(value)
    elif isinstance(value, (decimal.Decimal, float)):
        return formats.number_format(value)
    else:
        return smart_text(value) 
Example 31
Project: django-xadmin   Author: MarkHoo   File: export.py    MIT License 5 votes vote down vote up
def get_xlsx_export(self, context):
        datas = self._get_datas(context)
        output = io.BytesIO()
        export_header = (
            self.request.GET.get('export_xlsx_header', 'off') == 'on')

        model_name = self.opts.verbose_name
        book = xlsxwriter.Workbook(output)
        sheet = book.add_worksheet(
            u"%s %s" % (_(u'Sheet'), force_text(model_name)))
        styles = {'datetime': book.add_format({'num_format': 'yyyy-mm-dd hh:mm:ss'}),
                  'date': book.add_format({'num_format': 'yyyy-mm-dd'}),
                  'time': book.add_format({'num_format': 'hh:mm:ss'}),
                  'header': book.add_format({'font': 'name Times New Roman', 'color': 'red', 'bold': 'on', 'num_format': '#,##0.00'}),
                  'default': book.add_format()}

        if not export_header:
            datas = datas[1:]
        for rowx, row in enumerate(datas):
            for colx, value in enumerate(row):
                if export_header and rowx == 0:
                    cell_style = styles['header']
                else:
                    if isinstance(value, datetime.datetime):
                        cell_style = styles['datetime']
                    elif isinstance(value, datetime.date):
                        cell_style = styles['date']
                    elif isinstance(value, datetime.time):
                        cell_style = styles['time']
                    else:
                        cell_style = styles['default']
                sheet.write(rowx, colx, value, cell_style)
        book.close()

        output.seek(0)
        return output.getvalue() 
Example 32
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: util.py    MIT License 5 votes vote down vote up
def time(self):
        """
        :return:
            A datetime.time object of the time
        """

        return time(self.hour, self.minute, self.second, self.microsecond, self.tzinfo) 
Example 33
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: util.py    MIT License 5 votes vote down vote up
def dst(self):
        """
        :return:
            None or a datetime.timedelta() of the daylight savings time offset
        """

        if self.tzinfo is None:
            return None
        return self.tzinfo.dst(self.replace(year=2000)) 
Example 34
Project: flasky   Author: RoseOu   File: base.py    MIT License 5 votes vote down vote up
def bind_processor(self, dialect):
        def process(value):
            if isinstance(value, datetime.datetime):
                value = datetime.datetime.combine(
                    self.__zero_date, value.time())
            elif isinstance(value, datetime.time):
                value = datetime.datetime.combine(self.__zero_date, value)
            return value
        return process 
Example 35
Project: flasky   Author: RoseOu   File: base.py    MIT License 5 votes vote down vote up
def result_processor(self, dialect, coltype):
        def process(value):
            if isinstance(value, datetime.datetime):
                return value.time()
            elif isinstance(value, util.string_types):
                return datetime.time(*[
                    int(x or 0)
                    for x in self._reg.match(value).groups()])
            else:
                return value
        return process 
Example 36
Project: flasky   Author: RoseOu   File: base.py    MIT License 5 votes vote down vote up
def define_constraint_match(self, constraint):
        if constraint.match is not None:
            raise exc.CompileError(
                "MySQL ignores the 'MATCH' keyword while at the same time "
                "causes ON UPDATE/ON DELETE clauses to be ignored.")
        return "" 
Example 37
Project: flasky   Author: RoseOu   File: encoding.py    MIT License 5 votes vote down vote up
def is_protected_type(obj):
    """Determine if the object instance is of a protected type.

    Objects of protected types are preserved as-is when passed to
    force_unicode(strings_only=True).
    """
    return isinstance(obj, (
        six.integer_types +
        (types.NoneType,
         datetime.datetime, datetime.date, datetime.time,
         float, Decimal))
    ) 
Example 38
Project: kw_condition   Author: coreanq   File: main.py    MIT License 5 votes vote down vote up
def waitingTradeSystemStateEntered(self):
        # 장시작 전에 조건이 시작하도록 함 
        time_span = datetime.timedelta(minutes = 40)
        expected_time = (self.currentTime + time_span).time()
        if( expected_time >= datetime.time(*AUTO_TRADING_OPERATION_TIME[0][0]) ):
            self.sigSelectCondition.emit()       

            # 반환값 : 조건인덱스1^조건명1;조건인덱스2^조건명2;…;
            # result = '조건인덱스1^조건명1;조건인덱스2^조건명2;'
            result = self.getConditionNameList()
            searchPattern = r'(?P<index>[^\/:*?"<>|;]+)\^(?P<name>[^\/:*?"<>|;]+);'
            fileSearchObj = re.compile(searchPattern, re.IGNORECASE)
            findList = fileSearchObj.findall(result)
            
            tempDict = dict(findList)
            print(tempDict)
            
            condition_num = 0 
            for number, condition in tempDict.items():
                if condition == CONDITION_NAME:
                        condition_num = int(number)
            print("select condition" + kw_util.sendConditionScreenNo, CONDITION_NAME)
            self.sendCondition(kw_util.sendConditionScreenNo, CONDITION_NAME, condition_num,   1)

            
        else:
            QTimer.singleShot(1000, self.sigWaitingTrade)

        pass 
Example 39
Project: kw_condition   Author: coreanq   File: main.py    MIT License 5 votes vote down vote up
def onTimerSystemTimeout(self):
        # print(".", end='') 
        self.currentTime = datetime.datetime.now()
        if( self.getConnectState() != 1 ):
            util.save_log("Disconnected!", "시스템", folder = "log")
            self.sigDisconnected.emit() 
        else:
            if( datetime.time(*TRADING_INFO_GETTING_TIME) <=  self.currentTime.time() ): 
                self.timerSystem.stop()
                util.save_log("Stock Trade Terminate!\n\n\n\n\n", "시스템", folder = "log")
                pass
            else :
                pass
        pass 
Example 40
Project: Splunk_CBER_App   Author: MHaggis   File: rrule.py    MIT License 5 votes vote down vote up
def htimeset(self, hour, minute, second):
        tset = []
        rr = self.rrule
        for minute in rr._byminute:
            for second in rr._bysecond:
                tset.append(datetime.time(hour, minute, second,
                                         tzinfo=rr._tzinfo))
        tset.sort()
        return tset 
Example 41
Project: Splunk_CBER_App   Author: MHaggis   File: rrule.py    MIT License 5 votes vote down vote up
def mtimeset(self, hour, minute, second):
        tset = []
        rr = self.rrule
        for second in rr._bysecond:
            tset.append(datetime.time(hour, minute, second, tzinfo=rr._tzinfo))
        tset.sort()
        return tset 
Example 42
Project: Splunk_CBER_App   Author: MHaggis   File: rrule.py    MIT License 5 votes vote down vote up
def stimeset(self, hour, minute, second):
        return (datetime.time(hour, minute, second,
                tzinfo=self.rrule._tzinfo),) 
Example 43
Project: bigquerylayers   Author: smandaric   File: datetime_helpers.py    GNU General Public License v3.0 5 votes vote down vote up
def from_iso8601_time(value):
    """Convert a zoneless ISO8601 time string to a time.

    Args:
        value (str): The ISO8601 time string.

    Returns:
        datetime.time: A time equivalent to the time string.
    """
    return datetime.datetime.strptime(value, "%H:%M:%S").time() 
Example 44
Project: bigquerylayers   Author: smandaric   File: _helpers.py    GNU General Public License v3.0 5 votes vote down vote up
def _timestamp_query_param_from_json(value, field):
    """Coerce 'value' to a datetime, if set or not nullable.

    Args:
        value (str): The timestamp.
        field (.SchemaField): The field corresponding to the value.

    Returns:
        Optional[datetime.datetime]: The parsed datetime object from
        ``value`` if the ``field`` is not null (otherwise it is
        :data:`None`).
    """
    if _not_null(value, field):
        # Canonical formats for timestamps in BigQuery are flexible. See:
        # g.co/cloud/bigquery/docs/reference/standard-sql/data-types#timestamp-type
        # The separator between the date and time can be 'T' or ' '.
        value = value.replace(" ", "T", 1)
        # The UTC timezone may be formatted as Z or +00:00.
        value = value.replace("Z", "")
        value = value.replace("+00:00", "")

        if "." in value:
            # YYYY-MM-DDTHH:MM:SS.ffffff
            return datetime.datetime.strptime(value, _RFC3339_MICROS_NO_ZULU).replace(
                tzinfo=UTC
            )
        else:
            # YYYY-MM-DDTHH:MM:SS
            return datetime.datetime.strptime(value, _RFC3339_NO_FRACTION).replace(
                tzinfo=UTC
            )
    else:
        return None 
Example 45
Project: bigquerylayers   Author: smandaric   File: _helpers.py    GNU General Public License v3.0 5 votes vote down vote up
def _time_from_json(value, field):
    """Coerce 'value' to a datetime date, if set or not nullable"""
    if _not_null(value, field):
        if len(value) == 8:  # HH:MM:SS
            fmt = _TIMEONLY_WO_MICROS
        elif len(value) == 15:  # HH:MM:SS.micros
            fmt = _TIMEONLY_W_MICROS
        else:
            raise ValueError("Unknown time format: {}".format(value))
        return datetime.datetime.strptime(value, fmt).time() 
Example 46
Project: bigquerylayers   Author: smandaric   File: _helpers.py    GNU General Public License v3.0 5 votes vote down vote up
def _timestamp_to_json_parameter(value):
    """Coerce 'value' to an JSON-compatible representation.

    This version returns the string representation used in query parameters.
    """
    if isinstance(value, datetime.datetime):
        if value.tzinfo not in (None, UTC):
            # Convert to UTC and remove the time zone info.
            value = value.replace(tzinfo=None) - value.utcoffset()
        value = "%s %s+00:00" % (value.date().isoformat(), value.time().isoformat())
    return value 
Example 47
Project: bigquerylayers   Author: smandaric   File: _helpers.py    GNU General Public License v3.0 5 votes vote down vote up
def bigquery_scalar_type(value):
    """Return a BigQuery name of the scalar type that matches the given value.

    If the scalar type name could not be determined (e.g. for non-scalar
    values), ``None`` is returned.

    Args:
        value (Any)

    Returns:
        Optional[str]: The BigQuery scalar type name.
    """
    if isinstance(value, bool):
        return "BOOL"
    elif isinstance(value, numbers.Integral):
        return "INT64"
    elif isinstance(value, numbers.Real):
        return "FLOAT64"
    elif isinstance(value, decimal.Decimal):
        return "NUMERIC"
    elif isinstance(value, six.text_type):
        return "STRING"
    elif isinstance(value, six.binary_type):
        return "BYTES"
    elif isinstance(value, datetime.datetime):
        return "DATETIME" if value.tzinfo is None else "TIMESTAMP"
    elif isinstance(value, datetime.date):
        return "DATE"
    elif isinstance(value, datetime.time):
        return "TIME"

    return None 
Example 48
Project: bigquerylayers   Author: smandaric   File: _helpers.py    GNU General Public License v3.0 5 votes vote down vote up
def dst(self, dt):  # pylint: disable=unused-argument
        """Daylight savings time offset."""
        return self._dst 
Example 49
Project: AshsSDK   Author: thehappydinoa   File: rrule.py    MIT License 5 votes vote down vote up
def htimeset(self, hour, minute, second):
        tset = []
        rr = self.rrule
        for minute in rr._byminute:
            for second in rr._bysecond:
                tset.append(datetime.time(hour, minute, second,
                                          tzinfo=rr._tzinfo))
        tset.sort()
        return tset 
Example 50
Project: AshsSDK   Author: thehappydinoa   File: rrule.py    MIT License 5 votes vote down vote up
def mtimeset(self, hour, minute, second):
        tset = []
        rr = self.rrule
        for second in rr._bysecond:
            tset.append(datetime.time(hour, minute, second, tzinfo=rr._tzinfo))
        tset.sort()
        return tset 
Example 51
Project: AshsSDK   Author: thehappydinoa   File: rrule.py    MIT License 5 votes vote down vote up
def stimeset(self, hour, minute, second):
        return (datetime.time(hour, minute, second,
                tzinfo=self.rrule._tzinfo),) 
Example 52
Project: InsightAgent   Author: insightfinder   File: collectdReportMetrics.py    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 53
Project: InsightAgent   Author: insightfinder   File: collectdReportMetrics.py    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 54
Project: InsightAgent   Author: insightfinder   File: collectdReportMetrics.py    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 55
Project: pytracts   Author: rmorlok   File: to_json_test.py    Apache License 2.0 5 votes vote down vote up
def test_dict_field_encode(self):
        class GrabBag(messages.Message):
            item_count = messages.IntegerField()
            items = messages.DictField()

        gb = GrabBag()
        self.assertEquals('{}', to_json.encode_message(gb))

        gb = GrabBag()
        gb.item_count = 123
        self.assertEquals('{"item_count": 123}', to_json.encode_message(gb))

        gb = GrabBag()
        gb.item_count = 123
        gb.items = {}
        self.assertEquals('{"items": {}, "item_count": 123}', to_json.encode_message(gb))

        gb = GrabBag()
        gb.item_count = 123
        gb.items = {'a': 'b', 'foo': 'bar'}
        self.assertEquals('{"items": {"a": "b", "foo": "bar"}, "item_count": 123}', to_json.encode_message(gb))

        gb = GrabBag()
        gb.items = {'a': datetime(2010, 11, 13, 14, 15, 16), 'b': date(2009, 10, 11), 'c': time(1, 2, 3)}
        self.assertEquals('{"items": {"a": "2010-11-13T14:15:16", "c": "01:02:03", "b": "2009-10-11"}}', to_json.encode_message(gb))

        gb = GrabBag()
        gb.items = {'nested': {'a': datetime(2010, 11, 13, 14, 15, 16), 'b': date(2009, 10, 11), 'c': time(1, 2, 3)}}
        self.assertEquals('{"items": {"nested": {"a": "2010-11-13T14:15:16", "c": "01:02:03", "b": "2009-10-11"}}}', to_json.encode_message(gb)) 
Example 56
Project: tri.form   Author: TriOptima   File: test_forms.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_time():
    shortcut_test(
        Field.time,
        raw_and_parsed_data_tuples=[
            ('12:34:56', time(12, 34, 56)),
        ],
        normalizing=[
            ('2:34:56', '02:34:56'),
        ],
    ) 
Example 57
Project: rowgenerators   Author: Metatab   File: times.py    MIT License 5 votes vote down vote up
def cast_time(v, header_d, errors):
    if v is None or v is NoneValue or v == '':
        return None
    elif isinstance(v, time):
        return v
    elif isinstance(v, ValueType):
        return v.__time__()
    elif isinstance(v, str):
        return parse(v).time

    errors[header_d].add(u"Failed to cast '{}' ({}) to time in '{}': {}".format(v, type(v), header_d, v.exc))
    count_errors(errors)
    return None 
Example 58
Project: where   Author: kartverket   File: gnss_antenna_correction.py    MIT License 5 votes vote down vote up
def _used_date(self, satellite, given_date):
        """Choose correct date for use of satellite antenna corrections

        Satellite antenna correction are time dependent.

        Args:
            satellite (str):              Satellite identifier.
            given_date (datetime.date):   Given date used for finding corresponding time period in ANTEX file
        """
        used_date = None
        # TODO: Would it be not better to define rundate as datetime.datetime instead datetime.date?
        given_date = datetime.datetime.combine(given_date, datetime.time())  # conversion from date to datetime

        for date in sorted(self.data[satellite]):
            if date <= given_date:
                used_date = date

        if (used_date is None) or (given_date > self.data[satellite][used_date]["valid_until"]):
            log.warn(
                "No satellite phase center offset is given for satellite {} and date {}.",
                satellite,
                given_date,
                satellite,
            )

        return used_date 
Example 59
Project: openhatch   Author: campbe13   File: test_tzinfo.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def testUnknownOffsets(self):
        # This tzinfo behavior is required to make
        # datetime.time.{utcoffset, dst, tzname} work as documented.

        dst_tz = pytz.timezone('US/Eastern')

        # This information is not known when we don't have a date,
        # so return None per API.
        self.assertTrue(dst_tz.utcoffset(None) is None)
        self.assertTrue(dst_tz.dst(None) is None)
        # We don't know the abbreviation, but this is still a valid
        # tzname per the Python documentation.
        self.assertEqual(dst_tz.tzname(None), 'US/Eastern') 
Example 60
Project: openhatch   Author: campbe13   File: test_tzinfo.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def testHourBefore(self):
        # Python's datetime library has a bug, where the hour before
        # a daylight savings transition is one hour out. For example,
        # at the end of US/Eastern daylight savings time, 01:00 EST
        # occurs twice (once at 05:00 UTC and once at 06:00 UTC),
        # whereas the first should actually be 01:00 EDT.
        # Note that this bug is by design - by accepting this ambiguity
        # for one hour one hour per year, an is_dst flag on datetime.time
        # became unnecessary.
        self._test_all(
                self.transition_time - timedelta(hours=1), self.after
                ) 
Example 61
Project: openhatch   Author: campbe13   File: test_tzinfo.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def test_belfast(self):
        # Belfast uses London time.
        self.assertTrue('Europe/Belfast' in pytz.all_timezones_set)
        self.assertFalse('Europe/Belfast' in pytz.common_timezones)
        self.assertFalse('Europe/Belfast' in pytz.common_timezones_set) 
Example 62
Project: openhatch   Author: campbe13   File: test_utils_serialize.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def test_encode_decode(self):
        sr = self.spref
        sp1 = self.spider1
        sp2 = self.spider2
        ref1 = sr.get_reference_from_spider(sp1)
        ref2 = sr.get_reference_from_spider(sp2)
        dt = datetime.datetime(2010, 1, 2, 10, 11, 12)
        dts = "2010-01-02 10:11:12"
        d = datetime.date(2010, 1, 2)
        ds = "2010-01-02"
        t = datetime.time(10, 11, 12)
        ts = "10:11:12"
        dec = Decimal("1000.12")
        decs = "1000.12"

        examples_encode_decode = [
            ('lala', 'lala'),
            (sp1, ref1),
            (['lala', sp1], ['lala', ref1]),
            ({'lala': sp1}, {'lala': ref1}),
            ({sp1: sp2}, {ref1: ref2}),
            ({sp1: {sp2: ['lala', sp1]}}, {ref1: {ref2: ['lala', ref1]}})
        ]
        for spiders, refs in examples_encode_decode:
            self.assertEqual(self.encoder.encode(spiders), json.dumps(refs))
            self.assertEqual(self.decoder.decode(json.dumps(refs)), spiders)

        examples_encode_only = [
            ({sp1: dt}, {ref1: dts}),
            ({sp1: d}, {ref1: ds}),
            ({sp1: t}, {ref1: ts}),
            ({sp1: dec}, {ref1: decs}),
        ]
        for spiders, refs in examples_encode_only:
            self.assertEqual(self.encoder.encode(spiders), json.dumps(refs))

        assert 'Deferred' in self.encoder.encode(defer.Deferred()) 
Example 63
Project: deb-python-cassandra-driver   Author: openstack   File: util.py    Apache License 2.0 5 votes vote down vote up
def unix_time_from_uuid1(uuid_arg):
    """
    Converts a version 1 :class:`uuid.UUID` to a timestamp with the same precision
    as :meth:`time.time()` returns.  This is useful for examining the
    results of queries returning a v1 :class:`~uuid.UUID`.

    :param uuid_arg: a version 1 :class:`~uuid.UUID`
    """
    return (uuid_arg.time - 0x01B21DD213814000) / 1e7 
Example 64
Project: deb-python-cassandra-driver   Author: openstack   File: util.py    Apache License 2.0 5 votes vote down vote up
def hour(self):
        """
        The hour component of this time (0-23)
        """
        return self.nanosecond_time // Time.HOUR 
Example 65
Project: deb-python-cassandra-driver   Author: openstack   File: util.py    Apache License 2.0 5 votes vote down vote up
def minute(self):
        """
        The minute component of this time (0-59)
        """
        minutes = self.nanosecond_time // Time.MINUTE
        return minutes % 60 
Example 66
Project: deb-python-cassandra-driver   Author: openstack   File: util.py    Apache License 2.0 5 votes vote down vote up
def nanosecond(self):
        """
        The fractional seconds component of the time, in nanoseconds
        """
        return self.nanosecond_time % Time.SECOND 
Example 67
Project: deb-python-cassandra-driver   Author: openstack   File: util.py    Apache License 2.0 5 votes vote down vote up
def time(self):
        """
        Return a built-in datetime.time (nanosecond precision truncated to micros).
        """
        return datetime.time(hour=self.hour, minute=self.minute, second=self.second,
                             microsecond=self.nanosecond // Time.MICRO) 
Example 68
Project: deb-python-cassandra-driver   Author: openstack   File: util.py    Apache License 2.0 5 votes vote down vote up
def _from_timestring(self, s):
        try:
            parts = s.split('.')
            base_time = time.strptime(parts[0], "%H:%M:%S")
            self.nanosecond_time = (base_time.tm_hour * Time.HOUR +
                                    base_time.tm_min * Time.MINUTE +
                                    base_time.tm_sec * Time.SECOND)

            if len(parts) > 1:
                # right pad to 9 digits
                nano_time_str = parts[1] + "0" * (9 - len(parts[1]))
                self.nanosecond_time += int(nano_time_str)

        except ValueError:
            raise ValueError("can't interpret %r as a time" % (s,)) 
Example 69
Project: deb-python-cassandra-driver   Author: openstack   File: util.py    Apache License 2.0 5 votes vote down vote up
def __eq__(self, other):
        if isinstance(other, Time):
            return self.nanosecond_time == other.nanosecond_time

        if isinstance(other, six.integer_types):
            return self.nanosecond_time == other

        return self.nanosecond_time % Time.MICRO == 0 and \
            datetime.time(hour=self.hour, minute=self.minute, second=self.second,
                          microsecond=self.nanosecond // Time.MICRO) == other 
Example 70
Project: deb-python-cassandra-driver   Author: openstack   File: datatype_utils.py    Apache License 2.0 5 votes vote down vote up
def update_datatypes():
    _cass_version, _cql_version = get_server_versions()

    if _cass_version >= (2, 1, 0):
        COLLECTION_TYPES.add('tuple')

    if _cass_version >= (2, 2, 0):
        PRIMITIVE_DATATYPES.update(['date', 'time', 'smallint', 'tinyint'])
        PRIMITIVE_DATATYPES_KEYS.update(['date', 'time', 'smallint', 'tinyint'])
    if _cass_version >= (3, 10):
        PRIMITIVE_DATATYPES.add('duration')

    global SAMPLE_DATA
    SAMPLE_DATA = get_sample_data() 
Example 71
Project: deb-python-cassandra-driver   Author: openstack   File: test_udts.py    Apache License 2.0 5 votes vote down vote up
def test_can_insert_udts_protocol_v4_datatypes(self):
        """
        Test for inserting all protocol v4 column types into a UserType

        test_can_insert_udts_protocol_v4_datatypes tests that each protocol v4 cqlengine column type can be inserted
        into a UserType. It first creates a UserType that has each protocol v4 cqlengine column type, and a corresponding
        table/Model. It then creates a UserType instance where all the fields have corresponding data, and inserts the
        UserType as an instance of the Model. Finally, it verifies that each column read from the UserType from Cassandra
        is the same as the input parameters.

        @since 2.6.0
        @jira_ticket PYTHON-245
        @expected_result The UserType is inserted with each protocol v4 column type, and the resulting read yields proper data for each column.

        @test_category data_types:udt
        """

        if PROTOCOL_VERSION < 4:
            raise unittest.SkipTest("Protocol v4 datatypes in UDTs require native protocol 4+, currently using: {0}".format(PROTOCOL_VERSION))

        class Allv4Datatypes(UserType):
            a = columns.Date()
            b = columns.SmallInt()
            c = columns.Time()
            d = columns.TinyInt()

        class Allv4DatatypesModel(Model):
            id = columns.Integer(primary_key=True)
            data = columns.UserDefinedType(Allv4Datatypes)

        sync_table(Allv4DatatypesModel)
        self.addCleanup(drop_table, Allv4DatatypesModel)

        input = Allv4Datatypes(a=Date(date(1970, 1, 1)), b=32523, c=Time(time(16, 47, 25, 7)), d=123)
        Allv4DatatypesModel.create(id=0, data=input)

        self.assertEqual(1, Allv4DatatypesModel.objects.count())
        output = Allv4DatatypesModel.objects.first().data

        for i in range(ord('a'), ord('a') + 3):
            self.assertEqual(input[chr(i)], output[chr(i)]) 
Example 72
Project: deb-python-cassandra-driver   Author: openstack   File: test_model_io.py    Apache License 2.0 5 votes vote down vote up
def test_model_instantiation_save_and_load(self):
        """
        Tests that models can be saved and retrieved, this time using the
        natural model instantiation.
        """
        tm = TestModel(count=8, text='123456789')
        # Tests that values are available on instantiation.
        self.assertIsNotNone(tm['id'])
        self.assertEqual(tm.count, 8)
        self.assertEqual(tm.text, '123456789')
        tm.save()
        tm2 = TestModel.objects(id=tm.id).first()

        for cname in tm._columns.keys():
            self.assertEqual(getattr(tm, cname), getattr(tm2, cname)) 
Example 73
Project: deb-python-cassandra-driver   Author: openstack   File: test_model_io.py    Apache License 2.0 5 votes vote down vote up
def test_can_insert_model_with_all_protocol_v4_column_types(self):
        """
        Test for inserting all protocol v4 column types into a Model

        test_can_insert_model_with_all_protocol_v4_column_types tests that each cqlengine protocol v4 column type can be
        inserted into a Model. It first creates a Model that has each cqlengine protocol v4 column type. It then creates
        a Model instance where all the fields have corresponding data, which performs the insert into the Cassandra table.
        Finally, it verifies that each column read from the Model from Cassandra is the same as the input parameters.

        @since 2.6.0
        @jira_ticket PYTHON-245
        @expected_result The Model is inserted with each protocol v4 column type, and the resulting read yields proper data for each column.

        @test_category data_types:primitive
        """

        if PROTOCOL_VERSION < 4:
            raise unittest.SkipTest("Protocol v4 datatypes require native protocol 4+, currently using: {0}".format(PROTOCOL_VERSION))

        class v4DatatypesModel(Model):
            id = columns.Integer(primary_key=True)
            a = columns.Date()
            b = columns.SmallInt()
            c = columns.Time()
            d = columns.TinyInt()

        sync_table(v4DatatypesModel)

        input = [Date(date(1970, 1, 1)), 32523, Time(time(16, 47, 25, 7)), 123]

        v4DatatypesModel.create(id=0, a=date(1970, 1, 1), b=32523, c=time(16, 47, 25, 7), d=123)

        self.assertEqual(1, v4DatatypesModel.objects.count())
        output = v4DatatypesModel.objects.first()

        for i, i_char in enumerate(range(ord('a'), ord('a') + 3)):
            self.assertEqual(input[i], output[chr(i_char)]) 
Example 74
Project: deb-python-cassandra-driver   Author: openstack   File: test_validation.py    Apache License 2.0 5 votes vote down vote up
def test_datetime_date_support(self):
        today = date.today()
        self.DatetimeTest.objects.create(test_id=2, created_at=today)
        dt2 = self.DatetimeTest.objects(test_id=2).first()
        self.assertEqual(dt2.created_at.isoformat(), datetime(today.year, today.month, today.day).isoformat())

        result = self.DatetimeTest.objects.all().allow_filtering().filter(test_id=2).first()
        self.assertEqual(result.created_at, datetime.combine(today, datetime.min.time()))

        result = self.DatetimeTest.objects.all().allow_filtering().filter(test_id=2, created_at=today).first()
        self.assertEqual(result.created_at, datetime.combine(today, datetime.min.time())) 
Example 75
Project: deb-python-cassandra-driver   Author: openstack   File: test_validation.py    Apache License 2.0 5 votes vote down vote up
def setUpClass(cls):
        if PROTOCOL_VERSION < 4 or CASSANDRA_VERSION < "3.0":
            return
        
        cls.db_klass, cls.python_klass = UserDefinedType, User
        cls.first_value = User(
            age=1,
            date_param=datetime.utcnow(),
            map_param={1: time(2, 12, 7, 50), 2: util.Time(time(2, 12, 7, 49))},
            list_param=[datetime(1, 1, 2), datetime(1, 1, 3)],
            set_param=set((datetime(1, 1, 3), util.Date(datetime(1, 1, 1)))),
            tuple_param=(datetime(1, 1, 3), 2, False, 1, 2.324, uuid4())
        )

        cls.second_value = User(
            age=1,
            date_param=datetime.utcnow(),
            map_param={1: time(2, 12, 7, 50), 2: util.Time(time(2, 12, 7, 49))},
            list_param=[datetime(1, 1, 2), datetime(1, 2, 3)],
            set_param=None,
            tuple_param=(datetime(1, 1, 2), 2, False, 1, 2.324, uuid4())
        )

        cls.third_value = User(
            age=2,
            date_param=None,
            map_param={1: time(2, 12, 7, 51), 2: util.Time(time(2, 12, 7, 49))},
            list_param=[datetime(1, 1, 2), datetime(1, 1, 4)],
            set_param=set((datetime(1, 1, 3), util.Date(datetime(1, 1, 2)))),
            tuple_param=(None, 3, False, None, 2.3214, uuid4())
        )

        cls.model_class = UserModel
        sync_table(cls.model_class) 
Example 76
Project: deb-python-cassandra-driver   Author: openstack   File: test_validation.py    Apache License 2.0 5 votes vote down vote up
def test_timeuuid_io(self):
        """
        ensures that
        :return:
        """
        t0 = self.TimeUUIDTest.create(test_id=0)
        t1 = self.TimeUUIDTest.get(test_id=0)

        assert t1.timeuuid.time == t1.timeuuid.time 
Example 77
Project: tri.form   Author: TriOptima   File: test_forms.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def test_parse_errors():
    def post_validation(form):
        form.add_error('General snafu')
    form = MyTestForm(
        data=dict(
            party='foo',
            username='bar_foo',
            joined='foo',
            staff='foo',
            admin='foo',
            a_date='fooasd',
            a_time='asdasd',
            multi_choice_field=['q'],
            **{'-': ''}
        ),
        post_validation=post_validation)

    assert form.is_valid() is False

    assert form.errors == {'General snafu'}

    assert form.fields_by_name['party'].parsed_data == 'foo'
    assert form.fields_by_name['party'].errors == {'foo not in available choices'}
    assert form.fields_by_name['party'].value is None

    assert form.fields_by_name['username'].parsed_data == 'bar_foo'
    assert form.fields_by_name['username'].errors == {'Username must begin with "foo_"'}
    assert form.fields_by_name['username'].value is None

    assert form.fields_by_name['joined'].raw_data == 'foo'
    assert_one_error_and_matches_reg_exp(form.fields_by_name['joined'].errors, 'Time data "foo" does not match any of the formats .*')
    assert form.fields_by_name['joined'].parsed_data is None
    assert form.fields_by_name['joined'].value is None

    assert form.fields_by_name['staff'].raw_data == 'foo'
    assert form.fields_by_name['staff'].parsed_data is None
    assert form.fields_by_name['staff'].value is None

    assert form.fields_by_name['admin'].raw_data == 'foo'
    assert form.fields_by_name['admin'].parsed_data is None
    assert form.fields_by_name['admin'].value is None

    assert form.fields_by_name['a_date'].raw_data == 'fooasd'
    assert_one_error_and_matches_reg_exp(form.fields_by_name['a_date'].errors, "time data u?'fooasd' does not match format u?'%Y-%m-%d'")
    assert form.fields_by_name['a_date'].parsed_data is None
    assert form.fields_by_name['a_date'].value is None
    assert form.fields_by_name['a_date'].rendered_value == form.fields_by_name['a_date'].raw_data

    assert form.fields_by_name['a_time'].raw_data == 'asdasd'
    assert_one_error_and_matches_reg_exp(form.fields_by_name['a_time'].errors, "time data u?'asdasd' does not match format u?'%H:%M:%S'")
    assert form.fields_by_name['a_time'].parsed_data is None
    assert form.fields_by_name['a_time'].value is None

    assert form.fields_by_name['multi_choice_field'].raw_data_list == ['q']
    assert_one_error_and_matches_reg_exp(form.fields_by_name['multi_choice_field'].errors, "q not in available choices")
    assert form.fields_by_name['multi_choice_field'].parsed_data_list == ['q']
    assert form.fields_by_name['multi_choice_field'].value_list is None

    with pytest.raises(AssertionError):
        form.apply(Struct()) 
Example 78
Project: algobowl   Author: jackrosenthal   File: helpers.py    MIT License 4 votes vote down vote up
def ftime(dt, duration=None, show_day=False):
    """
    Format a ``date``, ``datetime``, or ``time`` object for view on
    the page. Optionally takes a duration to show a range of time.

    :param dt: A ``date``, ``datetime`` or ``time`` to format.
    :param duration: A ``timedelta`` indicating how long something
                     lasts.
    :param show_day: Show the day of the week.
    :rtype: string
    """
    if show_day:
        date_fmt = tg.config.get('locale.dow_date_fmt', '%A, %B %-d, %Y')
    else:
        date_fmt = tg.config.get('locale.date_fmt', '%B %-d, %Y')
    time_fmt = tg.config.get('locale.time_fmt', '%-I:%M %p')
    dt_sep = tg.config.get('locale.dt_sep', ' at ')
    dt_duration_sep = tg.config.get('locale.dt_duration_sep', ' from ')
    duration_time_sep = tg.config.get('locale.duration_time_sep', ' to ')

    if isinstance(duration, timedelta):
        # convert a duration to an end date
        duration = dt + duration

    if duration is not None and duration < dt:
        raise ValueError("Duration cannot be before the specified time")

    if isinstance(dt, datetime):
        if duration is None:
            # Format date without duration
            return dt.strftime(date_fmt + dt_sep + time_fmt)
        elif isinstance(duration, datetime):
            # Format date with duration
            start = (dt.strftime(date_fmt + dt_duration_sep + time_fmt)
                     + duration_time_sep)
            if duration - dt < timedelta(hours=24):
                return start + duration.strftime(time_fmt)
            return start + duration.strftime(date_fmt + dt_sep + time_fmt)
        else:
            raise TypeError("duration must be a timedelta or datetime")

    if isinstance(dt, date):
        return dt.strftime(date_fmt)

    if isinstance(dt, time):
        return dt.strftime(time_fmt) 
Example 79
Project: deb-python-cassandra-driver   Author: openstack   File: util.py    Apache License 2.0 4 votes vote down vote up
def uuid_from_time(time_arg, node=None, clock_seq=None):
    """
    Converts a datetime or timestamp to a type 1 :class:`uuid.UUID`.

    :param time_arg:
      The time to use for the timestamp portion of the UUID.
      This can either be a :class:`datetime` object or a timestamp
      in seconds (as returned from :meth:`time.time()`).
    :type datetime: :class:`datetime` or timestamp

    :param node:
      None integer for the UUID (up to 48 bits). If not specified, this
      field is randomized.
    :type node: long

    :param clock_seq:
      Clock sequence field for the UUID (up to 14 bits). If not specified,
      a random sequence is generated.
    :type clock_seq: int

    :rtype: :class:`uuid.UUID`

    """
    if hasattr(time_arg, 'utctimetuple'):
        seconds = int(calendar.timegm(time_arg.utctimetuple()))
        microseconds = (seconds * 1e6) + time_arg.time().microsecond
    else:
        microseconds = int(time_arg * 1e6)

    # 0x01b21dd213814000 is the number of 100-ns intervals between the
    # UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00.
    intervals = int(microseconds * 10) + 0x01b21dd213814000

    time_low = intervals & 0xffffffff
    time_mid = (intervals >> 32) & 0xffff
    time_hi_version = (intervals >> 48) & 0x0fff

    if clock_seq is None:
        clock_seq = random.getrandbits(14)
    else:
        if clock_seq > 0x3fff:
            raise ValueError('clock_seq is out of range (need a 14-bit value)')

    clock_seq_low = clock_seq & 0xff
    clock_seq_hi_variant = 0x80 | ((clock_seq >> 8) & 0x3f)

    if node is None:
        node = random.getrandbits(48)

    return uuid.UUID(fields=(time_low, time_mid, time_hi_version,
                             clock_seq_hi_variant, clock_seq_low, node), version=1) 
Example 80
Project: django-xadmin   Author: MarkHoo   File: export.py    MIT License 2 votes vote down vote up
def get_xls_export(self, context):
        datas = self._get_datas(context)
        output = io.BytesIO()
        export_header = (
            self.request.GET.get('export_xls_header', 'off') == 'on')

        model_name = self.opts.verbose_name
        book = xlwt.Workbook(encoding='utf8')
        sheet = book.add_sheet(
            u"%s %s" % (_(u'Sheet'), force_text(model_name)))
        styles = {'datetime': xlwt.easyxf(num_format_str='yyyy-mm-dd hh:mm:ss'),
                  'date': xlwt.easyxf(num_format_str='yyyy-mm-dd'),
                  'time': xlwt.easyxf(num_format_str='hh:mm:ss'),
                  'header': xlwt.easyxf('font: name Times New Roman, color-index red, bold on', num_format_str='#,##0.00'),
                  'default': xlwt.Style.default_style}

        if not export_header:
            datas = datas[1:]
        for rowx, row in enumerate(datas):
            for colx, value in enumerate(row):
                if export_header and rowx == 0:
                    cell_style = styles['header']
                else:
                    if isinstance(value, datetime.datetime):
                        cell_style = styles['datetime']
                    elif isinstance(value, datetime.date):
                        cell_style = styles['date']
                    elif isinstance(value, datetime.time):
                        cell_style = styles['time']
                    else:
                        cell_style = styles['default']
                sheet.write(rowx, colx, value, style=cell_style)
        book.save(output)

        output.seek(0)
        return output.getvalue()