當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。