我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用datetime.date.fromtimestamp()。
def get_context_data(self, **kwargs): """ Get the context data to render the result page. """ page = kwargs['page'] length, results = self.object_list max_pages = int(math.ceil(float(length) / self.RESULTS_PER_PAGE)) return { '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': results, 'search_time': kwargs['time'], 'now': date.fromtimestamp(time.time()) }
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(). """
def DateFromTicks(self, secs): """ Returns an object representing the date *secs* seconds after the epoch. For example: .. python:: import time d = db.DateFromTicks(time.time()) This method is equivalent to the module-level ``DateFromTicks()`` method in an underlying DB API-compliant module. :Parameters: secs : int the seconds from the epoch :return: an object containing the date """ date = date.fromtimestamp(secs) return self.__driver.get_import().Date(date.year, date.month, date.day)
def Time(self, hour, minute, second): """ Returns an object representing the specified time. This method is equivalent to the module-level ``Time()`` method in an underlying DB API-compliant module. :Parameters: hour the hour of the day minute the minute within the hour. 0 <= *minute* <= 59 second the second within the minute. 0 <= *second* <= 59 :return: an object containing the time """ dt = datetime.fromtimestamp(secs) return self.__driver.get_import().Time(dt.hour, dt.minute, dt.second)
def TimeFromTicks(self, secs): """ Returns an object representing the time 'secs' seconds after the epoch. For example: .. python:: import time d = db.TimeFromTicks(time.time()) This method is equivalent to the module-level ``TimeFromTicks()`` method in an underlying DB API-compliant module. :Parameters: secs : int the seconds from the epoch :return: an object containing the time """ dt = datetime.fromtimestamp(secs) return self.__driver.get_import().Time(dt.hour, dt.minute, dt.second)
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
def doBackup(self): configfile.save() if config.plugins.softwaremanager.epgcache.value: eEPGCache.getInstance().save() try: if not path.exists(self.backuppath): makedirs(self.backuppath) self.backupdirs = ' '.join( config.plugins.configurationbackup.backupdirs.value ) if path.exists(self.fullbackupfilename): dt = str(date.fromtimestamp(stat(self.fullbackupfilename).st_ctime)) self.newfilename = self.backuppath + "/" + dt + '-' + self.backupfile if path.exists(self.newfilename): remove(self.newfilename) rename(self.fullbackupfilename,self.newfilename) if self.finished_cb: self.session.openWithCallback(self.finished_cb, Console, title = _("Backup is running..."), cmdlist = ["tar -czvf " + self.fullbackupfilename + " " + self.backupdirs],finishedCallback = self.backupFinishedCB,closeOnSuccess = True) else: self.session.open(Console, title = _("Backup is running..."), cmdlist = ["tar -czvf " + self.fullbackupfilename + " " + self.backupdirs],finishedCallback = self.backupFinishedCB, closeOnSuccess = True) except OSError: if self.finished_cb: self.session.openWithCallback(self.finished_cb, MessageBox, _("Sorry, your backup destination is not writeable.\nPlease select a different one."), MessageBox.TYPE_INFO, timeout = 10 ) else: self.session.openWithCallback(self.backupErrorCB,MessageBox, _("Sorry, your backup destination is not writeable.\nPlease select a different one."), MessageBox.TYPE_INFO, timeout = 10 )
def getFuzzyDay(t): d = localtime(t) nt = time() n = localtime() if d[:3] == n[:3]: # same day date = _("Today") elif dt_date.fromtimestamp(t) == dt_date.today() + dt_timedelta(days = 1): # next day date = _("Tomorrow") elif nt < t and (t - nt) < WEEKSECONDS: # same week date = WEEKDAYS[d.tm_wday] else: date = "%d.%d.%d" % (d.tm_mday, d.tm_mon, d.tm_year) return date # used to let timer pixmaps blink in our lists
def listEPGItems(self, cItem): printDBG("TvpVod.listEPGItems") sts, data = self._getPage(cItem['url'], self.defaultParams) if not sts: return try: #date.fromtimestamp(item['release_date']['sec']).strftime('%H:%M') data = byteify(json.loads(data)) data['items'].sort(key=lambda item: item['release_date_hour']) for item in data['items']: if not item.get('is_live', False): continue title = str(item['title']) desc = str(item['lead']) asset_id = str(item['asset_id']) asset_id = str(item['video_id']) icon = self.getImageUrl(item) desc = item['release_date_hour'] + ' - ' + item['broadcast_end_date_hour'] + '[/br]' + desc self.addVideo({'title':title, 'url':'', 'object_id':asset_id, 'icon':icon, 'desc':desc}) printDBG(data) except Exception: printExc()
def doBackup(self): configfile.save() if config.plugins.softwaremanager.epgcache.value: eEPGCache.getInstance().save() try: if (path.exists(self.backuppath) == False): makedirs(self.backuppath) self.backupdirs = ' '.join([sub("^/+", "", d) for d in config.plugins.configurationbackup.backupdirs.value]) if path.exists(self.fullbackupfilename): dt = str(date.fromtimestamp(stat(self.fullbackupfilename).st_ctime)) self.newfilename = self.backuppath + "/" + dt + '-' + self.backupfile if path.exists(self.newfilename): remove(self.newfilename) rename(self.fullbackupfilename,self.newfilename) if self.finished_cb: self.session.openWithCallback(self.finished_cb, Console, title = _("Backup is running..."), cmdlist = ["tar -C / -czvf " + self.fullbackupfilename + " " + self.backupdirs], finishedCallback = self.backupFinishedCB,closeOnSuccess = True) else: self.session.open(Console, title = _("Backup is running..."), cmdlist = ["tar -C / -czvf " + self.fullbackupfilename + " " + self.backupdirs], finishedCallback = self.backupFinishedCB, closeOnSuccess = True) except OSError: if self.finished_cb: self.session.openWithCallback(self.finished_cb, MessageBox, _("Sorry, your backup destination is not writeable.\nPlease select a different one."), MessageBox.TYPE_INFO, timeout = 10 ) else: self.session.openWithCallback(self.backupErrorCB,MessageBox, _("Sorry, your backup destination is not writeable.\nPlease select a different one."), MessageBox.TYPE_INFO, timeout = 10 )
def _x_format(self): """Return the value formatter for this graph""" def date_to_str(x): d = date.fromtimestamp(x) return self.x_value_formatter(d) return date_to_str
def today(): """Return the current local time. This is equivalent to date.fromtimestamp(time.time())"""
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(). """
def today(): """Return the current local datetime, with tzinfo None. This is equivalent to datetime.fromtimestamp(time.time()). See also now(), fromtimestamp(). """
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(). """
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")])
def available_data_range(self, frequency): if frequency != 'tick': raise NotImplementedError s = date.today() e = date.fromtimestamp(2147483647) return s, e
def notify_status(self, node, status): _template = 'info.jinja' if status == 'success': _template = 'user_success.jinja' elif status == 'error': _template = 'error.jinja' for tenant in node.get('tenants'): for user in tenant.get('users'): if 'email' in user: subject = '[' + status + '] Evacuation Status' template_vars = { 'name': user.get('name'), 'tenant': tenant.get('id'), 'instances': tenant.get('instances'), 'evacuation_time': date.fromtimestamp(time.time()) } message = load_jinja_templates(self.templates_dir, _template, template_vars) self.send_email(self.notify_from, user.get('email'), subject, html_msg=message) # notify administrators subject = 'Host Evacuation status' _template = 'success.jinja' template_vars = { 'host': node.get('host'), 'tenants': node.get('tenants'), 'instances': node.get('instances'), 'hypervisor': node.get('details'), 'evacuation_time': date.fromtimestamp(time.time()) } message = load_jinja_templates(self.templates_dir, _template, template_vars) self.send_email(self.notify_from, self.notify_from, subject, message, self.admin_list or None)
def __init__(self, name, onfloor, room=None, missed=None): self.name = name today = date.fromtimestamp(time.time()) self.eval_date = today + timedelta(weeks=10) self.onfloor_status = onfloor self.room_number = room self.signatures_missed = missed
def after_read_item(self, value): return date.fromtimestamp(value * self.offset)
def test_fromtimestamp(self): self.assertEqual( date.fromtimestamp(0), Date.fromtimestamp(0) )
def fromtimestamp(cls, timestamp): """ Returns a NepDate object created from timestamp """ return NepDate.from_ad_date(date.fromtimestamp(timestamp))
def render_tweet_html(tweet): date_format = '%B %-d, %Y' context = { 'body': process_tweet_text(tweet), 'date': date.fromtimestamp(tweet.created_at_in_seconds).strftime(date_format) } return jinja2.Environment( loader=jinja2.FileSystemLoader('./') ).get_template('release_template.html').render(context)
def __init__(self, name, group, ds_id, start_time, end_time, data): super(PopulationTimeline, self).__init__({ 'name': name, 'group': group, 'data_source_id': ds_id, 'start_time': start_time, 'end_time': end_time, 'data': [(date.fromtimestamp(x[0]/1000), x[1]) for x in data] })
def cacheForFuture(self, headers): ten_years = 315569260 headers.setRawHeaders("Cache-Control",["max-age="+str(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")])
def get_after(self, timestamp, s=None): """ Find all the (available) logs that are after the given time stamp. Override this function in class LogFileOutput. Parameters: timestamp(datetime.datetime): lines before this time are ignored. s(str or list): one or more strings to search for. If not supplied, all available lines are searched. Yields: (dict): the parsed data of lines with timestamps after this date in the same format they were supplied. """ search_by_expression = self._valid_search(s) for line in self.lines: # If `s` is not None, keywords must be found in the line if s and not search_by_expression(line): continue info = self._parse_line(line) try: logtime = date.fromtimestamp(float(info.get('timestamp', 0))) if logtime > timestamp: yield info except: pass
def load_file(guid): file = None try: file = get_box_store().getNote(dev_token, guid, True, True, False, False) except Exception, e: return None file_content = parse_file(file.content) return { 'title': file.title, 'content': base64.b64decode(file_content + '=' * (-len(file_content) % 4)), 'created': date.fromtimestamp(file.created / 100).strftime('%d/%m/%Y') }
def datetime_format(time): return datetime.fromtimestamp(int(str(time)[:-3])).strftime('%Y-%m-%d %H:%M:%S')
def message(request): json_str = ((request.body).decode('utf-8')) received_json_data = json.loads(json_str) meal = received_json_data['content'] daystring = ["?", "?", "?", "?", "?", "?", "?"] today = datetime.datetime.today().weekday() nextdaystring = ["?", "?", "?", "?", "?", "?", "?"] today_date = datetime.date.today().strftime("%m? %d? ") tomorrow_date = date.fromtimestamp(time.time() + 60 * 60 * 24).strftime("%m? %d? ") if meal == '??' or meal == '??' or meal == '??': return JsonResponse({ 'message': { 'text': today_date + daystring[today] + '?? ' + meal + ' ?????. \n \n' + crawl(request) }, 'keyboard': { 'type': 'buttons', 'buttons': ['??', '??', '??', '??? ??', '??? ??', '??? ??'] } }) if meal == '??? ??' or meal == '??? ??' or meal == '??? ??': return JsonResponse({ 'message': { 'text': '[' + meal + '] \n' + tomorrow_date + nextdaystring[today] + '?? ?? ?????. \n \n' + crawl(request) }, 'keyboard': { 'type': 'buttons', 'buttons': ['??', '??', '??', '??? ??', '??? ??', '??? ??'] } }) # message ?? ??? ??? ??