Python datetime.date.fromtimestamp() Examples

The following are 30 code examples of datetime.date.fromtimestamp(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module datetime.date , or try the search function .
Example #1
Source File: federal_reserve.py    From stocklook with MIT License 6 votes vote down vote up
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 
Example #2
Source File: helpers.py    From Varken with MIT License 6 votes vote down vote up
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) 
Example #3
Source File: pytables.py    From elasticintel with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #4
Source File: TestSTARRDemographicsConversion.py    From CDSS with GNU General Public License v3.0 6 votes vote down vote up
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)]) 
Example #5
Source File: idatetime.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
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().
        """ 
Example #6
Source File: idatetime.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
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().
        """ 
Example #7
Source File: pytables.py    From Computable with MIT License 6 votes vote down vote up
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 
Example #8
Source File: pytables.py    From Splunking-Crime with GNU Affero General Public License v3.0 6 votes vote down vote up
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 
Example #9
Source File: idatetime.py    From learn_python3_spider with MIT License 6 votes vote down vote up
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`.
        """ 
Example #10
Source File: testcase.py    From ringcentral-python with MIT License 6 votes vote down vote up
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'
        }) 
Example #11
Source File: views.py    From ahmia-site with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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())
        } 
Example #12
Source File: testcase.py    From ringcentral-python with MIT License 6 votes vote down vote up
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'
        }) 
Example #13
Source File: csvimport.py    From sqlobject with GNU Lesser General Public License v2.1 6 votes vote down vote up
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)) 
Example #14
Source File: inactive_issues_scraper.py    From community with GNU Affero General Public License v3.0 5 votes vote down vote up
def run(issues):
    issues_number_list = []
    for j in issues:
        issue_no = j.number
        events = j.get_events()
        myevent_list = []
        data = []
        for i in events:
            myevent_list.append(str(i.event))
        for i in events:
            if i.commit_id is not None:
                data.append(str(i.created_at))
        for i, myevents in reversed(list(enumerate(myevent_list))):
            if myevents == 'unassigned':
                break
            elif myevents == 'assigned':
                a = events[i].created_at
                c = (date.fromtimestamp(time.time()) - a.date()).days
                if c >= 60:  # for checking assigned duration

                    mydata = list(reversed(data))
                    if len(mydata) != 0:
                        commit1 = parse(mydata[0])
                        calculated_days = (date.fromtimestamp(
                            time.time()) - commit1.date()).days
                        if calculated_days >= 60:
                            # for checking last commit update
                            issues_number_list.append(issue_no)
                    else:
                        issues_number_list.append(issue_no)
                break
    return issues_number_list 
Example #15
Source File: aggregations.py    From hepdata with GNU General Public License v2.0 5 votes vote down vote up
def parse_date_aggregations(buckets):
    for date_hit in buckets:
        timestamp = date.fromtimestamp(date_hit['key'] // 1000)
        date_hit['key'] = timestamp.year
        date_hit['url_params'] = {'date': date_hit['key']}

    buckets = sorted(buckets, key=lambda x: x['key'], reverse=True)
    buckets = sorted(buckets, key=lambda x: x['doc_count'], reverse=True)

    return {
        'type': 'date',
        'printable_name': 'Date',
        'vals': buckets,
        'max_values': MAX_DATE_FACETS
    } 
Example #16
Source File: idatetime.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def today():
        """Return the current local datetime, with tzinfo None.

        This is equivalent to datetime.fromtimestamp(time.time()).
        See also now(), fromtimestamp().
        """ 
Example #17
Source File: helper.py    From resilient-community-apps with MIT License 5 votes vote down vote up
def time_str():
    today = date.fromtimestamp(time.time())
    timestamp = time.strftime('%H:%M:%S')
    timenow = "{1} on {0}".format(today, timestamp)
    return timenow 
Example #18
Source File: time.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def date_time(self):
        return date.fromtimestamp(self.value_as_int / PNTimeResponse.MULTIPLIER) 
Example #19
Source File: test_dateformat.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_datetime_with_tzinfo(self):
        tz = get_fixed_timezone(-510)
        ltz = get_default_timezone()
        dt = make_aware(datetime(2009, 5, 16, 5, 30, 30), ltz)
        self.assertEqual(datetime.fromtimestamp(int(format(dt, 'U')), tz), dt)
        self.assertEqual(datetime.fromtimestamp(int(format(dt, 'U')), ltz), dt)
        # astimezone() is safe here because the target timezone doesn't have DST
        self.assertEqual(datetime.fromtimestamp(int(format(dt, 'U'))), dt.astimezone(ltz).replace(tzinfo=None))
        self.assertEqual(datetime.fromtimestamp(int(format(dt, 'U')), tz).utctimetuple(), dt.utctimetuple())
        self.assertEqual(datetime.fromtimestamp(int(format(dt, 'U')), ltz).utctimetuple(), dt.utctimetuple()) 
Example #20
Source File: base_activity.py    From canvas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def date(self):
        return date.fromtimestamp(self.ts) 
Example #21
Source File: test_dateformat.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_datetime_with_local_tzinfo(self):
        ltz = get_default_timezone()
        dt = make_aware(datetime(2009, 5, 16, 5, 30, 30), ltz)
        self.assertEqual(datetime.fromtimestamp(int(format(dt, 'U')), ltz), dt)
        self.assertEqual(datetime.fromtimestamp(int(format(dt, 'U'))), dt.replace(tzinfo=None)) 
Example #22
Source File: csvimport.py    From sqlobject with GNU Lesser General Public License v2.1 5 votes vote down vote up
def parse_date(v):
    v = v.strip()
    if not v:
        return None
    if v.startswith('NOW-') or v.startswith('NOW+'):
        days = int(v[3:])
        now = date.today()
        return now + timedelta(days)
    else:
        parsed = time.strptime(v, '%Y-%m-%d')
        return date.fromtimestamp(time.mktime(parsed)) 
Example #23
Source File: idatetime.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def utcfromtimestamp(timestamp):
        """Return the UTC datetime from the POSIX timestamp with tzinfo None.

        This may raise ValueError, if the timestamp is out of the range of
        values supported by the platform C gmtime() function. It's common for
        this to be restricted to years in 1970 through 2038.

        See also fromtimestamp().
        """ 
Example #24
Source File: header.py    From lbry-sdk with MIT License 5 votes vote down vote up
def estimated_julian_day(self, height):
        return date_to_julian_day(date.fromtimestamp(self.estimated_timestamp(height, False))) 
Example #25
Source File: idatetime.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def fromtimestamp(timestamp):
        """Return the local date from a POSIX timestamp (like time.time())

        This may raise ValueError, if the timestamp is out of the range of
        values supported by the platform C localtime() function. It's common
        for this to be restricted to years from 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().
        """ 
Example #26
Source File: idatetime.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def today():
        """Return the current local time.

        This is equivalent to date.fromtimestamp(time.time())""" 
Example #27
Source File: util.py    From recordexpungPDX with MIT License 5 votes vote down vote up
def fromtimestamp(t):
        return DateWithFuture(date=date_class.fromtimestamp(t)) 
Example #28
Source File: conftest.py    From notifications-admin with MIT License 5 votes vote down vote up
def mock_get_api_keys(mocker, fake_uuid):
    def _get_keys(service_id, key_id=None):
        keys = {'apiKeys': [
            api_key_json(id_=fake_uuid, name='some key name',),
            api_key_json(id_='1234567', name='another key name', expiry_date=str(date.fromtimestamp(0)))
        ]}
        return keys

    return mocker.patch('app.api_key_api_client.get_api_keys', side_effect=_get_keys) 
Example #29
Source File: invoices.py    From quay with Apache License 2.0 5 votes vote down vote up
def _format_timestamp(stripe_timestamp):
    if stripe_timestamp is None:
        return None
    date_obj = date.fromtimestamp(stripe_timestamp)
    return date_obj.strftime("%m/%d/%Y") 
Example #30
Source File: appcachepoison.py    From piSociEty with GNU General Public License v3.0 5 votes vote down vote up
def cacheForFuture(self, headers):
        ten_years = 315569260
        headers.setRawHeaders("Cache-Control",["max-age={}".format(ten_years)])
        headers.setRawHeaders("Last-Modified",["Mon, 29 Jun 1998 02:28:12 GMT"]) # it was modifed long ago, so is most likely fresh
        in_ten_years = date.fromtimestamp(time.time() + ten_years)
        headers.setRawHeaders("Expires",[in_ten_years.strftime("%a, %d %b %Y %H:%M:%S GMT")])