当前位置: 首页>>代码示例>>Python>>正文


Python date.fromtimestamp方法代码示例

本文整理汇总了Python中datetime.date.fromtimestamp方法的典型用法代码示例。如果您正苦于以下问题:Python date.fromtimestamp方法的具体用法?Python date.fromtimestamp怎么用?Python date.fromtimestamp使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在datetime.date的用法示例。


在下文中一共展示了date.fromtimestamp方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _unconvert_index

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import fromtimestamp [as 别名]
def _unconvert_index(data, kind, encoding=None):
    kind = _ensure_decoded(kind)
    if kind == u('datetime64'):
        index = DatetimeIndex(data)
    elif kind == u('datetime'):
        index = np.array([datetime.fromtimestamp(v) for v in data],
                         dtype=object)
    elif kind == u('date'):
        try:
            index = np.array(
                [date.fromordinal(v) for v in data], dtype=object)
        except (ValueError):
            index = np.array(
                [date.fromtimestamp(v) for v in data], dtype=object)
    elif kind in (u('integer'), u('float')):
        index = np.array(data)
    elif kind in (u('string')):
        index = _unconvert_string_array(data, nan_rep=None, encoding=encoding)
    elif kind == u('object'):
        index = np.array(data[0])
    else:  # pragma: no cover
        raise ValueError('unrecognized index type %s' % kind)
    return index 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:25,代码来源:pytables.py

示例2: fromtimestamp

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import fromtimestamp [as 别名]
def fromtimestamp(timestamp, tz=None):
        """Return the local date and time corresponding to the POSIX timestamp.

        Same as is returned by time.time(). If optional argument tz is None or
        not specified, the timestamp is converted to the platform's local date
        and time, and the returned datetime object is naive.

        Else tz must be an instance of a class tzinfo subclass, and the
        timestamp is converted to tz's time zone. In this case the result is
        equivalent to
        tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz)).

        fromtimestamp() may raise ValueError, if the timestamp is out of the
        range of values supported by the platform C localtime() or gmtime()
        functions. It's common for this to be restricted to years in 1970
        through 2038. Note that on non-POSIX systems that include leap seconds
        in their notion of a timestamp, leap seconds are ignored by
        fromtimestamp(), and then it's possible to have two timestamps
        differing by a second that yield identical datetime objects.

        See also utcfromtimestamp().
        """ 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:24,代码来源:idatetime.py

示例3: update

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import fromtimestamp [as 别名]
def update(self):
        today = date.today()

        try:
            dbdate = date.fromtimestamp(stat(self.dbfile).st_mtime)
            db_next_update = date.fromtimestamp(stat(self.dbfile).st_mtime) + timedelta(days=30)

        except FileNotFoundError:
            self.logger.error("Could not find MaxMind DB as: %s", self.dbfile)
            self.download()
            dbdate = date.fromtimestamp(stat(self.dbfile).st_mtime)
            db_next_update = date.fromtimestamp(stat(self.dbfile).st_mtime) + timedelta(days=30)

        if db_next_update < today:
            self.logger.info("Newer MaxMind DB available, Updating...")
            self.logger.debug("MaxMind DB date %s, DB updates after: %s, Today: %s",
                              dbdate, db_next_update, today)
            self.reader_manager(action='close')
            self.download()
            self.reader_manager(action='open')
        else:
            db_days_update = db_next_update - today
            self.logger.debug("MaxMind DB will update in %s days", abs(db_days_update.days))
            self.logger.debug("MaxMind DB date %s, DB updates after: %s, Today: %s",
                              dbdate, db_next_update, today) 
开发者ID:Boerderij,项目名称:Varken,代码行数:27,代码来源:helpers.py

示例4: fromtimestamp

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import fromtimestamp [as 别名]
def fromtimestamp(timestamp, tz=None):
        """Return the local date and time corresponding to the POSIX timestamp.

        Same as is returned by time.time(). If optional argument tz is None or
        not specified, the timestamp is converted to the platform's local date
        and time, and the returned datetime object is naive.

        Else tz must be an instance of a class tzinfo subclass, and the
        timestamp is converted to tz's time zone. In this case the result is
        equivalent to
        ``tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))``.

        fromtimestamp() may raise `ValueError`, if the timestamp is out of the
        range of values supported by the platform C localtime() or gmtime()
        functions. It's common for this to be restricted to years in 1970
        through 2038. Note that on non-POSIX systems that include leap seconds
        in their notion of a timestamp, leap seconds are ignored by
        fromtimestamp(), and then it's possible to have two timestamps
        differing by a second that yield identical datetime objects.

        .. seealso:: `utcfromtimestamp`.
        """ 
开发者ID:wistbean,项目名称:learn_python3_spider,代码行数:24,代码来源:idatetime.py

示例5: get_context_data

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import fromtimestamp [as 别名]
def get_context_data(self, **kwargs):
        """
        Get the context data to render the result page.
        """
        page = kwargs['page']
        length = self.object_list.total
        max_pages = int(math.ceil(float(length) / self.RESULTS_PER_PAGE))

        return {
            'suggest': self.object_list.suggest,
            'page': page + 1,
            'max_pages': max_pages,
            'result_begin': self.RESULTS_PER_PAGE * page,
            'result_end': self.RESULTS_PER_PAGE * (page + 1),
            'total_search_results': length,
            'query_string': kwargs['q'],
            'search_results': self.object_list.hits,
            'search_time': kwargs['time'],
            'now': date.fromtimestamp(time.time())
        } 
开发者ID:ahmia,项目名称:ahmia-site,代码行数:22,代码来源:views.py

示例6: presence_subscription_mock

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import fromtimestamp [as 别名]
def presence_subscription_mock(self, mock, id='1', detailed=True):
        detailed = '?detailedTelephonyState=true' if detailed else ''
        expires_in = 15 * 60 * 60

        return self.add(mock, 'POST', '/restapi/v1.0/subscription', {
            'eventFilters': ['/restapi/v1.0/account/~/extension/' + id + '/presence' + detailed],
            'expirationTime': date.fromtimestamp(time() + expires_in).isoformat(),
            'expiresIn': expires_in,
            'deliveryMode': {
                'transportType': 'PubNub',
                'encryption': True,
                'address': '123_foo',
                'subscriberKey': 'sub-c-foo',
                'secretKey': 'sec-c-bar',
                'encryptionAlgorithm': 'AES',
                'encryptionKey': 'e0bMTqmumPfFUbwzppkSbA=='
            },
            'creationTime': date.today().isoformat(),
            'id': 'foo-bar-baz',
            'status': 'Active',
            'uri': 'https://platform.ringcentral.com/restapi/v1.0/subscription/foo-bar-baz'
        }) 
开发者ID:ringcentral,项目名称:ringcentral-python,代码行数:24,代码来源:testcase.py

示例7: subscription_mock

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import fromtimestamp [as 别名]
def subscription_mock(self, mock, expires_in=54000, filters=None, id=None):
        if filters is None:
            filters = ['/restapi/v1.0/account/~/extension/1/presence']

        return self.add(mock, 'POST' if not id else 'PUT', '/restapi/v1.0/subscription' + ('/' + id if id else ''), {
            'eventFilters': filters,
            'expirationTime': date.fromtimestamp(time() + expires_in).isoformat(),
            'expiresIn': expires_in,
            'deliveryMode': {
                'transportType': 'PubNub',
                'encryption': False,
                'address': '123_foo',
                'subscriberKey': 'sub-c-foo',
                'secretKey': 'sec-c-bar'
            },
            'id': id if id else 'foo-bar-baz',
            'creationTime': date.today().isoformat(),
            'status': 'Active',
            'uri': 'https://platform.ringcentral.com/restapi/v1.0/subscription/foo-bar-baz'
        }) 
开发者ID:ringcentral,项目名称:ringcentral-python,代码行数:22,代码来源:testcase.py

示例8: _unconvert_index

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import fromtimestamp [as 别名]
def _unconvert_index(data, kind, encoding=None):
    kind = _ensure_decoded(kind)
    if kind == u('datetime64'):
        index = DatetimeIndex(data)
    elif kind == u('timedelta64'):
        index = TimedeltaIndex(data)
    elif kind == u('datetime'):
        index = np.asarray([datetime.fromtimestamp(v) for v in data],
                           dtype=object)
    elif kind == u('date'):
        try:
            index = np.asarray(
                [date.fromordinal(v) for v in data], dtype=object)
        except (ValueError):
            index = np.asarray(
                [date.fromtimestamp(v) for v in data], dtype=object)
    elif kind in (u('integer'), u('float')):
        index = np.asarray(data)
    elif kind in (u('string')):
        index = _unconvert_string_array(data, nan_rep=None, encoding=encoding)
    elif kind == u('object'):
        index = np.asarray(data[0])
    else:  # pragma: no cover
        raise ValueError('unrecognized index type %s' % kind)
    return index 
开发者ID:nccgroup,项目名称:Splunking-Crime,代码行数:27,代码来源:pytables.py

示例9: _get_raw

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import fromtimestamp [as 别名]
def _get_raw(fname):
    tree = ElementTree.fromstring(urllib.urlopen(_get_url(fname)).read())
    observations = tree.iter('observation')
    # Get dates
    dates = [date.fromtimestamp(mktime(strptime(obs.get('date'), '%Y-%m-%d'))) for obs in tree.iter('observation')]
    # Get values
    values = [obs.get('value') for obs in tree.iter('observation')]
    # FRED uses a "." to indicate that there is no data for a given date,
    # so we just do a zero-order interpolation here
    for i in range(len(values)):
        if values[i] == '.':
            values[i] = values[i-1]

    # Return dates and values in a nested list
    data = []
    for i in range(len(dates)):
        data.append[dates[i], float(values[i])]

    return data 
开发者ID:zbarge,项目名称:stocklook,代码行数:21,代码来源:federal_reserve.py

示例10: generate_test_data_row

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import fromtimestamp [as 别名]
def generate_test_data_row(curr_row, lifespan, patient_id):
        import time     # required to get current timestamp - it is here to not clash with datetime.time

        return (patient_id,
                date.fromtimestamp(lifespan[0]),
                [None, date.fromtimestamp(lifespan[1])][random.randint(0, 1)],
                GENDER[random.randint(0, len(GENDER) - 1)],
                RACE[random.randint(0, len(RACE) - 1)],
                ETHNICITY[random.randint(0, len(ETHNICITY) - 1)],
                MARITAL_STATUS[random.randint(0, len(MARITAL_STATUS) - 1)],
                RELIGION[random.randint(0, len(RELIGION) - 1)],
                LANGUAGE[random.randint(0, len(LANGUAGE) - 1)],
                [None, 'N', 'Y'][random.randint(0, 2)],
                ''.join(random.choice(string.ascii_uppercase) for _ in range(10)),
                'SS' + format(curr_row, '07'),
                date.fromtimestamp(random.randint(1, int(time.time()))),
                random.randint(150, 210),
                random.randint(50, 150),
                random.randint(18, 24),
                random.randint(1, 27),
                random.randint(0, 300),
                random.randint(0, 1000),
                PAT_STATUS[random.randint(0, len(PAT_STATUS) - 1)]) 
开发者ID:HealthRex,项目名称:CDSS,代码行数:25,代码来源:TestSTARRDemographicsConversion.py

示例11: parse_datetime

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import fromtimestamp [as 别名]
def parse_datetime(v):
    v = v.strip()
    if not v:
        return None
    if v.startswith('NOW-') or v.startswith('NOW+'):
        seconds = int(v[3:])
        now = datetime.now()
        return now + timedelta(0, seconds)
    else:
        fmts = ['%Y-%m-%dT%H:%M:%S',
                '%Y-%m-%d %H:%M:%S',
                '%Y-%m-%dT%H:%M',
                '%Y-%m-%d %H:%M']
        for fmt in fmts[:-1]:
            try:
                parsed = time.strptime(v, fmt)
                break
            except ValueError:
                pass
        else:
            parsed = time.strptime(v, fmts[-1])
        return datetime.fromtimestamp(time.mktime(parsed)) 
开发者ID:sqlobject,项目名称:sqlobject,代码行数:24,代码来源:csvimport.py

示例12: _unconvert_index

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import fromtimestamp [as 别名]
def _unconvert_index(data, kind, encoding=None, errors='strict'):
    kind = _ensure_decoded(kind)
    if kind == u'datetime64':
        index = DatetimeIndex(data)
    elif kind == u'timedelta64':
        index = TimedeltaIndex(data)
    elif kind == u'datetime':
        index = np.asarray([datetime.fromtimestamp(v) for v in data],
                           dtype=object)
    elif kind == u'date':
        try:
            index = np.asarray(
                [date.fromordinal(v) for v in data], dtype=object)
        except (ValueError):
            index = np.asarray(
                [date.fromtimestamp(v) for v in data], dtype=object)
    elif kind in (u'integer', u'float'):
        index = np.asarray(data)
    elif kind in (u'string'):
        index = _unconvert_string_array(data, nan_rep=None, encoding=encoding,
                                        errors=errors)
    elif kind == u'object':
        index = np.asarray(data[0])
    else:  # pragma: no cover
        raise ValueError('unrecognized index type {kind}'.format(kind=kind))
    return index 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:28,代码来源:pytables.py

示例13: readable_timestamp

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import fromtimestamp [as 别名]
def readable_timestamp(stamp):
    """
    :param stamp: A floating point number representing the POSIX file timestamp.
    :return: A short human-readable string representation of the timestamp.
    """
    if date.fromtimestamp(stamp) == date.today():
        return str(datetime.fromtimestamp(stamp).strftime("%I:%M:%S%p"))
    else:
        return str(date.fromtimestamp(stamp)) 
开发者ID:peterbrittain,项目名称:asciimatics,代码行数:11,代码来源:utilities.py

示例14: _unconvert_index

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import fromtimestamp [as 别名]
def _unconvert_index(data, kind, encoding=None, errors='strict'):
    kind = _ensure_decoded(kind)
    if kind == u('datetime64'):
        index = DatetimeIndex(data)
    elif kind == u('timedelta64'):
        index = TimedeltaIndex(data)
    elif kind == u('datetime'):
        index = np.asarray([datetime.fromtimestamp(v) for v in data],
                           dtype=object)
    elif kind == u('date'):
        try:
            index = np.asarray(
                [date.fromordinal(v) for v in data], dtype=object)
        except (ValueError):
            index = np.asarray(
                [date.fromtimestamp(v) for v in data], dtype=object)
    elif kind in (u('integer'), u('float')):
        index = np.asarray(data)
    elif kind in (u('string')):
        index = _unconvert_string_array(data, nan_rep=None, encoding=encoding,
                                        errors=errors)
    elif kind == u('object'):
        index = np.asarray(data[0])
    else:  # pragma: no cover
        raise ValueError('unrecognized index type %s' % kind)
    return index 
开发者ID:birforce,项目名称:vnpy_crypto,代码行数:28,代码来源:pytables.py

示例15: test_nasa_date

# 需要导入模块: from datetime import date [as 别名]
# 或者: from datetime.date import fromtimestamp [as 别名]
def test_nasa_date(self):
        sec_in_year = 60 * 60 * 24 * 365
        now = time.time()
        for i in range(100):
            offset = random.randint(15 * sec_in_year * -1, 10 * sec_in_year)
            test_date = date.fromtimestamp(now + offset)
            formatted = test_date.strftime('%Y-%m-%d')
            self.assertEqual(validations.nasa_date(formatted), formatted)
        self.assertRaises(ValueError, lambda: validations.nasa_date('tomorrow'))
        self.assertRaises(ValueError, lambda: validations.nasa_date('2015'))
        self.assertRaises(ValueError, lambda: validations.nasa_date('2015-01'))
        self.assertRaises(ValueError, lambda: validations.nasa_date('2015/01/04')) 
开发者ID:brendanv,项目名称:nasa-api,代码行数:14,代码来源:test_validations.py


注:本文中的datetime.date.fromtimestamp方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。