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


Python utils.to_timestamp函数代码示例

本文整理汇总了Python中utils.to_timestamp函数的典型用法代码示例。如果您正苦于以下问题:Python to_timestamp函数的具体用法?Python to_timestamp怎么用?Python to_timestamp使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


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

示例1: get_campaigns_by_bloodtype

def get_campaigns_by_bloodtype():
    session = db.Session()
    user_id = request.args.get('user_id', 0)

    # filter by user Blood Type
    user = session.query(db.User).filter_by(user_id=user_id).first()
    if not user:
        session.close()
        return ApiResponse({
            'status': 'error',
            'message': 'No user with id {0} found'.format(user_id)
        })

    campaigns_blood = session.query(db.CampaignBlood).filter_by(blood_type=user.blood_type).all()
    campaigns = [
        {
            'name': c.campaign.name,
            'hospital': {
                'name': c.campaign.hospital.name,
                'latitude': c.campaign.hospital.latitude,
                'longitude': c.campaign.hospital.longitude,
            },
            'message': c.campaign.message,
            'start_date': to_timestamp(c.campaign.start_date),
            'end_date': to_timestamp(c.campaign.end_date)
        } for c in campaigns_blood]
    session.close()

    # return data
    return ApiResponse({
        "campaigns": campaigns
    })
开发者ID:ani12321,项目名称:jap-jete-admin,代码行数:32,代码来源:client.py

示例2: create_campaign

def create_campaign():
    session = db.Session()
    data = json.loads(request.data)
    hospital_id = request.args.get('hospital_id', 0)

    # hospital = session.query(db.Hospital).filter_by(_id=hospital_id).first()
    hospital = session.query(db.Hospital).first()

    name = data['name']
    message = data['message']
    bloodtypes = data['bloodtypes']
    start_date = datetime.datetime.now()
    end_date = datetime.datetime.now() + datetime.timedelta(days=10)
    campaign = db.Campaign(hospital._id, name, message, start_date, end_date)
    session.add(campaign)
    session.commit()

    for bloodtype in bloodtypes:
        campaign_blood = db.CampaignBlood(campaign._id, bloodtype)
        session.add(campaign_blood)

    session.commit()

    gcmClient = GCMClient(api_key=os.environ.get('GCM_API_KEY'))
    alert = {
        'subject': 'Fushate e re',
        'message': campaign.hospital.name,
        'data': {
            'id': campaign._id,
            'name': name,
            'hospital': {
                'name': campaign.hospital.name,
                'latitude': campaign.hospital.latitude,
                'longitude': campaign.hospital.longitude,
            },
            'message': message,
            'start_date': to_timestamp(start_date),
            'end_date': to_timestamp(end_date)
        }
    }

    interested_users = session.query(db.User).filter(db.User.blood_type.in_(bloodtypes))
    gcm_id_list = [user.gcm_id for user in interested_users]
    session.close()

    response = gcmClient.send(gcm_id_list, alert, time_to_live=3600)
    if response:
        return ApiResponse({
            'status': 'ok'
        })
    else:
        return ApiResponse({
            'status': 'some error occurred'
        })
开发者ID:ani12321,项目名称:jap-jete-admin,代码行数:54,代码来源:hospitals.py

示例3: as_dicts

 def as_dicts(self, convert_timestamps=False):
     """
     Returns dictionary form of Global Tag object.
     """
     json_gt = {
         'name': self.name,
         'validity': self.validity,
         'description': self.description,
         'release': self.release,
         'insertion_time': to_timestamp(self.insertion_time) if convert_timestamps else self.insertion_time,
         'snapshot_time': to_timestamp(self.snapshot_time) if convert_timestamps else self.snapshot_time,
         'scenario': self.scenario,
         'workflow': self.workflow,
         'type': self.type
     }
     return json_gt
开发者ID:BetterWang,项目名称:cmssw,代码行数:16,代码来源:models.py

示例4: user_past_donations

def user_past_donations(user_id=None):
    session = db.Session()

    if user_id is None:
        user_id = request.args.get('user_id', 0)

    user = session.query(db.User).filter_by(user_id=user_id).first()
    if not user:
        session.close()
        return ApiResponse({
            'status': 'error',
            'message': 'No user with id {0} found'.format(id)
        })

    donations = session.query(db.UserHistory).filter_by(user_id=user.user_id).all()
    result = {
        'user': user.user_id,
        'history': [{
            'date': to_timestamp(d.donation_date),
            'amount': d.amount,
            'hospital': d.hospital.name
        } for d in donations]
    }
    session.close()
    return ApiResponse({
        'history': result
    })
开发者ID:ani12321,项目名称:jap-jete-admin,代码行数:27,代码来源:client.py

示例5: output_date

    def output_date(self, date, start, dt_format=None):
        """
        Output lines with the date.
        Output starts from the block at "start" position and
         ends when the date is no longer met.
        Next blocks reads as needed.

        :param date: string with some date
        :type date: str
        :param start: a start position of a block
        :type start: int
        :param dt_format: format of the date
        :type dt_format: str
        """
        if dt_format:
            self._set_dt_format(dt_format)

        stamp = to_timestamp(date, self.dt_format)
        block = _Range(start, self._get_end_of_block(start))

        rest = self._print_stamp_from_block(block, stamp)
        while rest:
            block_start = block.end
            block_end = self._get_end_of_block(block_start)

            rest = self._print_stamp_from_block(
                _Range(block_start, block_end), stamp, rest)
开发者ID:srg91,项目名称:bzseeker,代码行数:27,代码来源:seeker.py

示例6: send_blob

	def send_blob(self, payload, upload_session_id):
		"""
		Send the BLOB of a payload over HTTP.
		The BLOB is put in the request body, so no additional processing has to be done on the server side, apart from decoding from base64.
		"""
		# encode the BLOB data of the Payload to make sure we don't send a character that will influence the HTTPs request
		blob_data = base64.b64encode(payload["data"])

		url_data = {"database" : self.data_to_send["destinationDatabase"], "upload_session_id" : upload_session_id}

		# construct the data to send in the body and header of the HTTPs request
		for key in payload.keys():
			# skip blob
			if key != "data":
				if key == "insertion_time":
					url_data[key] = to_timestamp(payload[key])
				else:
					url_data[key] = payload[key]

		request = url_query(url=self._SERVICE_URL + "store_payload/", url_data=url_data, body=blob_data)

		# send the request and return the response
		# Note - the url_query module will handle retries, and will throw a NoMoreRetriesException if it runs out
		try:
			request_response = request.send()
			return request_response
		except Exception as e:
			# make sure we don't try again - if a NoMoreRetriesException has been thrown, retries have run out
			if isinstance(e, errors.NoMoreRetriesException):
				self._outputter.write("\t\t\tPayload with hash '%s' was not uploaded because the maximum number of retries was exceeded." % payload["hash"])
				self._outputter.write("Payload with hash '%s' was not uploaded because the maximum number of retries was exceeded." % payload["hash"])
			return json.dumps({"error" : str(e), "traceback" : traceback.format_exc()})
开发者ID:hotdrinkbrian,项目名称:cmssw,代码行数:32,代码来源:uploads.py

示例7: _adjust_timecode

def _adjust_timecode(episode, timestamp):
    '''
    Offset a timecode by the total number of offset frames
    '''
    frame = timestamp_to_seconds(timestamp)
    offsets = episode.offsets
    if episode.is_pioneer:
        offsets = episode.pioneer_offsets
    series = episode.series
    total_offset = 0
    # calculate offset from frame data
    if isinstance(offsets, list):
        # for list-types (movies, not episodes), start with 0 offset
        for o in offsets:
            if frame > frame_to_seconds(o['frame']):
                total_offset += frame_to_seconds(o['offset'])
    else:
        # episodes are map-based, with a key for each chapter
        # orange bricks have a delay on the OP subs
        if (series == 'DBZ' and not episode.is_r1dbox and
           frame < frame_to_seconds(offsets['prologue']["frame"])):
            total_offset += _op_subtitle_delay(episode)
        for key in offsets.keys():
            # also account for ED subs being +0.333 s early
            if frame > frame_to_seconds(offsets[key]["frame"]):
                total_offset += frame_to_seconds(
                    offsets[key]["offset"])
    # apply offset to subtitle timing
    frame -= total_offset

    return to_timestamp(frame)
开发者ID:gravitypriest,项目名称:dragon-radar,代码行数:31,代码来源:subtitle.py

示例8: add_satz

 def add_satz(self, fullname, result, date):
     s = self.get_schuetze_by_fullname(fullname)
     entry = JSONSatz(
         schuetze_uuid=s.uuid,
         result=result,
         date=utils.to_timestamp(date))
     self.data.append(entry)
     self._generic_add_data(entry, self.settings.data_file)
     return entry
开发者ID:hikhvar,项目名称:Stats,代码行数:9,代码来源:json_model.py

示例9: __init__

 def __init__(self, dictionary={}, convert_timestamps=True):
     # assign each entry in a kwargs
     for key in dictionary:
         try:
             if convert_timestamps:
                 self.__dict__[key] = to_timestamp(dictionary[key])
             else:
                 self.__dict__[key] = dictionary[key]
         except KeyError as k:
             continue
开发者ID:BetterWang,项目名称:cmssw,代码行数:10,代码来源:models.py

示例10: all_campaigns

def all_campaigns():
    session = db.Session()
    hospital_id = request.args.get('hospital_id', 0)
    #campaigns = session.query(db.Campaign).filter_by(hospital_id=hospital_id).all()
    campaigns = session.query(db.Campaign).all()

    bloodtypes = session.query()
    response = ApiResponse({
        'campaigns': [
            {
                'id': c._id,
                'name': c.name,
                'message': c.message,
                'start_date': to_timestamp(c.start_date),
                'end_date': to_timestamp(c.end_date),
                'active': c.active,
                'bloodtypes': [r.blood_type for r in c.requirement]
            } for c in campaigns]
    })
    session.close()
    return response
开发者ID:ani12321,项目名称:jap-jete-admin,代码行数:21,代码来源:hospitals.py

示例11: safe_handler

 def safe_handler(*args, **kwargs):
     session = db.Session()
     session_token = request.args.get('session_token', '')
     user_id = request.args.get('user_id', 0)
     user = session.query(db.User).filter_by(user_id=user_id).first()
     if user and utils.str_equal(user.session_token, session_token) and \
         utils.to_timestamp(user.session_token_expires_at) > time.time():
         response = handler(*args, **kwargs)
     else:
         response = ApiResponse(config.ACCESS_DENIED_MSG, status='403')
     session.close()
     return response
开发者ID:ani12321,项目名称:jap-jete-admin,代码行数:12,代码来源:decorators.py

示例12: dashboard

def dashboard():
    ops = db_fieldbook.get_all_opportunities()
    for op in ops:
        if op["status"] == "Accepted":
            op["class"] = "success"
        elif op["status"] == "Offered":
            op["class"] = "info"
        elif op["status"] == "Expired":
            op["class"] = "active"
        elif op["status"] == "Attended":
            op["class"] = "active"
        elif op["status"] == "Not Attended":
            op["class"] = "active"
        op["remaining_mins"] = int(int(op["expiry_time"] - utils.to_timestamp(datetime.datetime.utcnow())) / 60)
    return render_template('dashboard.html', ops=ops, dash_refresh_timeout=config.dash_refresh_timeout)
开发者ID:nhshd-slot,项目名称:slot,代码行数:15,代码来源:controller.py

示例13: login

def login():
    data = json.loads(request.data)
    user_id = data['user_id']
    gcmID = data['gcmID']
    fb_token = data['fb_token']

    payload= {
        'access_token': fb_token,
        'fields': 'id'
    }
    fb_response = requests.get(config.FB_ENDPOINT, params=payload).json()
    if 'error' in fb_response:
        return ApiResponse(config.ACCESS_DENIED_MSG, status='403')
    elif user_id != fb_response['id']:
        return ApiResponse(config.ACCESS_DENIED_MSG, status='403')

    # Facebook login was successful
    user = session.query(User).filter_by(user_id=user_id).first()
    gcm_id = request.args.get('gcm_id', '')
    blood_type = request.args.get('blood_type', '')

    if user:
        user.fb_token = fb_token
        token, expires_at = User.generate_session_token()
        user.session_token = token
        user.session_token_expires_at = expires_at
        if gcm_id:
            user.gcm_id = gcm_id
        if blood_type:
            user.blood_type = blood_type
        session.commit()
    else:
        user = User(user_id, fb_token=fb_token, gcm_id=gcm_id,
                    blood_type=blood_type)
        session.add(user)
        session.commit()

    if user:
        return ApiResponse({
            'status': 'OK',
            'session_token': user.session_token,
            'expires_at': to_timestamp(user.session_token_expires_at)
        })
    else:
        return ApiResponse({
            'status': 'Failed',
            'message': "Couldn't create new user"
        })
开发者ID:abello,项目名称:jap-jete-admin,代码行数:48,代码来源:views.py

示例14: login

def login():
    session = db.Session()
    data = json.loads(request.data)
    user_id = data['user_id']
    gcm_id = data['gcm_id']
    fb_token = data['fb_token']

    payload = {
        'access_token': fb_token,
        'fields': ['id', 'name']
    }
    fb_response = requests.get(config.FB_ENDPOINT, params=payload).json()
    if 'error' in fb_response:
        return ApiResponse(config.ACCESS_DENIED_MSG, status='403')
    elif user_id != fb_response['id']:
        return ApiResponse(config.ACCESS_DENIED_MSG, status='403')

    # Facebook login was successful
    user = session.query(db.User).filter_by(user_id=user_id).first()

    if user:
        user.fb_token = fb_token
        token, expires_at = db.User.generate_session_token()
        user.session_token = token
        user.session_token_expires_at = expires_at
        if gcm_id:
            user.gcm_id = gcm_id
    else:
        name = fb_response['name'].split()
        user = db.User(user_id, name[0], name[-1], fb_token=fb_token, gcm_id=gcm_id)
                    #blood_type=blood_type)
        session.add(user)
    session.commit()

    response = ApiResponse({
        'status': 'OK',
        'session_token': user.session_token,
        'expires_at': to_timestamp(user.session_token_expires_at)
    } if user else {
        'status': 'Failed',
        'message': "Couldn't create new user"
    })
    session.close()
    return response
开发者ID:ani12321,项目名称:jap-jete-admin,代码行数:44,代码来源:client.py

示例15: seek

    def seek(self, date, dt_format=None):
        """
        Search the start position of date in a bzipped log file.

        :param date: string with some date
        :type date: str
        :return: position of day
        """
        if dt_format:
            self._set_dt_format(dt_format)

        stamp = to_timestamp(date, self.dt_format)
        block = self._get_block_with_date(stamp)
        if not block:
            return

        if block.start == block.end:
            block.end = self._get_end_of_block(block.end)

        return block
开发者ID:srg91,项目名称:bzseeker,代码行数:20,代码来源:seeker.py


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