• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python pytz.UTC类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: prepara_certificado_txt

    def prepara_certificado_txt(self, cert_txt):
        #
        # Para dar certo a leitura pelo xmlsec, temos que separar o certificado
        # em linhas de 64 caracteres de extensão...
        #
        cert_txt = cert_txt.replace('\n', '')
        cert_txt = cert_txt.replace('-----BEGIN CERTIFICATE-----', '')
        cert_txt = cert_txt.replace('-----END CERTIFICATE-----', '')

        linhas_certificado = ['-----BEGIN CERTIFICATE-----\n']
        for i in range(0, len(cert_txt), 64):
            linhas_certificado.append(cert_txt[i:i+64] + '\n')
        linhas_certificado.append('-----END CERTIFICATE-----\n')

        self.certificado = ''.join(linhas_certificado)

        cert_openssl = crypto.load_certificate(crypto.FILETYPE_PEM, self.certificado)
        self.cert_openssl = cert_openssl

        self._emissor = dict(cert_openssl.get_issuer().get_components())
        self._proprietario = dict(cert_openssl.get_subject().get_components())
        self._numero_serie = cert_openssl.get_serial_number()
        self._data_inicio_validade = datetime.strptime(cert_openssl.get_notBefore(), '%Y%m%d%H%M%SZ')
        self._data_inicio_validade = UTC.localize(self._data_inicio_validade)
        self._data_fim_validade    = datetime.strptime(cert_openssl.get_notAfter(), '%Y%m%d%H%M%SZ')
        self._data_fim_validade    = UTC.localize(self._data_fim_validade)

        for i in range(cert_openssl.get_extension_count()):
            extensao = cert_openssl.get_extension(i)
            self._extensoes[extensao.get_short_name()] = extensao.get_data()
开发者ID:Anferi,项目名称:PySPED,代码行数:30,代码来源:certificado.py


示例2: unixtimestamp

def unixtimestamp(datetime):
    """Get unix time stamp from that given datetime. If datetime
    is not tzaware then it's assumed that it is UTC
    """
    epoch = UTC.localize(datetime.utcfromtimestamp(0))
    if not datetime.tzinfo:
        dt = UTC.localize(datetime)
    else:
        dt = UTC.normalize(datetime)
    delta = dt - epoch
    return total_seconds(delta)
开发者ID:20tab,项目名称:python-gmaps,代码行数:11,代码来源:timezone.py


示例3: on_topicinfo

    def on_topicinfo(self, c, e):
        model.Session.remove()
        args = e.arguments()
        log.debug(args)
        channel = args[0].lstrip(''.join(CHANNEL_PREFIXES))
        changed_by = args[1]
        changed_on = UTC.localize(datetime.utcfromtimestamp(float(args[2])))

        channel_participation_id = self.channels[channel]
        channel_participation = model.Session.query(model.ChannelParticipation) \
            .get(channel_participation_id)
        channel_info = model.Session.query(model.ChannelTopicInfo) \
                        .get(channel_participation_id)
        if not channel_info:
            log.debug('on_topicinfo ChannelTopicInfo for %s non-existant' % channel)
            channel_info = model.ChannelTopicInfo(channel_participation,
                                                  changed_by, changed_on)
        else:
            if channel_info.changed_by != changed_by or \
                channel_info.changed_on != changed_on:
                log.debug(self.__class__.__name__ + ' updating topic info for channel %s...' % channel)
                if channel_info.changed_by != changed_by:
                    channel_info.changed_by = changed_by
                if channel_info.changed_on != changed_on:
                    channel_info.changed_on = changed_on
        model.Session.save(channel_info)
        model.Session.commit()
开发者ID:UfSoft,项目名称:oil,代码行数:27,代码来源:network.py


示例4: format_date

def format_date(date, tzinfo=None):

    ### TODO: calling this function with the Plone default datetime (year=1000)
    ### will generate exceptions.  This case must be handled
    ### This can be aggrivated by requesting an article that does not exist, 
    ### through articles.xml view, among other ways.

    #Are we a datetime or a DateTime?
    if hasattr(date, 'utcdatetime'): #we are a Zope DateTime!
        date = date.utcdatetime()

    #else: #we are a python datetime!
    #    date = date

    #calling this function 'naive' will attach a UTC timezone
    if date.tzinfo is None and tzinfo is None:
        date = UTC.localize(date)

    #calling this function with a tzinfo arg will:
    elif tzinfo is not None:
        if date.tzinfo is None: #localize an existing naive datetime
            date = tzinfo.localize(date)
        else: #convert a non-naive datetime into the provided timezone
            date = date.astimezone(tzinfo)

    if date.tzinfo.tzname(date) is not None:
        return date.strftime("%a, %d %b %Y %H:%M:%S %Z")
    else: #we only have a UTC offset
        return date.strftime("%a, %d %b %Y %H:%M:%S %z")
开发者ID:RadioFreeAsia,项目名称:mobapp,代码行数:29,代码来源:Types.py


示例5: load_resp

    def load_resp(self, resp, is_download):
        """
        Loads json response from API.

        :param resp: Response from API
        :type resp: dictionary
        :param is_download: Calculates time taken based on 'updated' field in response if upload, and based on stop time if download
        :type is_download: boolean
        """

        assert isinstance(resp, dict)
        setattr(self, 'resp', resp)
        setattr(self, 'size', humanize.naturalsize(int(resp['size'])))

        if is_download:
            updated_at = datetime.now(UTC)
        else:
            updated_at = UTC.localize(datetime.strptime(resp['updated'], '%Y-%m-%dT%H:%M:%S.%fZ'))

        setattr(self, 'time_taken', dict(zip(
            ('m', 's'),
            divmod((updated_at - getattr(self, 'start_time')).seconds if updated_at > getattr(self, 'start_time') else 0, 60)
        )))

        setattr(self, 'full_path', 'gs://%s/%s' % (resp['bucket'], resp['name']))
开发者ID:danielpoonwj,项目名称:gwrappy,代码行数:25,代码来源:utils.py


示例6: to_utc

def to_utc(dt):
    if not isinstance(dt, datetime):
        dt = datetime(dt.year, dt.month, dt.day)
    if dt.tzinfo is None:
        return UTC.localize(dt)
    else:
        return dt.astimezone(UTC)
开发者ID:altaurog,项目名称:pgcopy,代码行数:7,代码来源:util.py


示例7: build_feed

    def build_feed(self):
        "Build the feed given our existing URL"
        # Get all the episodes
        page_content = str(requests.get(self.url).content)
        parser = BassdriveParser()
        parser.feed(page_content)
        links = parser.get_links()

        # And turn them into something usable
        fg = FeedGenerator()
        fg.id(self.url)
        fg.title(self.title)
        fg.description(self.title)
        fg.author({'name': self.dj})
        fg.language('en')
        fg.link({'href': self.url, 'rel': 'alternate'})
        fg.logo(self.logo)

        for link in links:
            fe = fg.add_entry()
            fe.author({'name': self.dj})
            fe.title(link[0])
            fe.description(link[0])
            fe.enclosure(self.url + link[1], 0, 'audio/mpeg')

            # Bassdrive always uses date strings of
            # [yyyy.mm.dd] with 0 padding on days and months,
            # so that makes our lives easy
            date_start = link[0].find('[')
            date_str = link[0][date_start:date_start+12]
            published = datetime.strptime(date_str, '[%Y.%m.%d]')
            fe.pubdate(UTC.localize(published))
            fe.guid((link[0]))

        return fg
开发者ID:bspeice,项目名称:elektricity,代码行数:35,代码来源:bassdrive.py


示例8: activities_and_calories

def activities_and_calories(gauge_factory, config, logger):
    activity_gauge = gauge_factory('runkeeper.activities')
    calorie_gauge = gauge_factory('runkeeper.calories_burned')
    local_tz = timezone(config['runkeeper.local_tz'])

    user = healthgraph.User(session=healthgraph.
                            Session(config['runkeeper.access_token']))
    activities_iter = user.get_fitness_activity_iter()

    today = today_utc().date()
    today_activities = []
    for a in activities_iter:  # breaking early prevents loading all results
        activity_time = a['start_time'].replace(tzinfo=local_tz)
        activity_time_utc = UTC.normalize(activity_time)
        day = activity_time_utc.date()
        if day == today:
            today_activities.append(a)
        elif (today - day).days > 2:
            break

    total_activities = len(today_activities)
    total_calories = int(sum([a['total_calories'] for a in today_activities]))

    activity_gauge.save(today_utc(), total_activities)
    calorie_gauge.save(today_utc(), total_calories)
    logger.info('Saved {0} activities ({1} cal) for {2}'
                .format(total_activities, total_calories, today_utc()))
开发者ID:Glavin001,项目名称:personal-dashboard,代码行数:27,代码来源:runkeeper.py


示例9: load

    def load(self, timestamp):
        """Return (stored_datetime, loaded_datetime).

        The stored_datetime is the timestamp actually stored in
        Postgres, which may or may not be the timestamp we saved. The
        loaded_datetime is the timestamp we end up with using this
        method.
        """
        select = {
            'timestamp_explicit':
            "timestamp at time zone '{}'".format(self.tz.zone),
            'timestamp_stored': "timestamp at time zone 'UTC'",
        }

        loaded_attr = ('timestamp' if self.conversion == 'implicit'
                       else 'timestamp_explicit')

        qs = Timestamp.objects.extra(select=select)

        timestamp = qs.get(pk=timestamp.pk)

        stored_datetime = UTC.localize(timestamp.timestamp_stored)
        loaded_datetime = self.tz.localize(getattr(timestamp, loaded_attr))

        return stored_datetime, loaded_datetime
开发者ID:Mondego,项目名称:pyreco,代码行数:25,代码来源:allPythonContent.py


示例10: list_events

def list_events():
    """List events for ajax supplied start and end."""
    start = request.args.get('start', 0, type=int)
    end = request.args.get('end', 0, type=int)
    # make a datetime from the timestamp
    start = datetime.datetime.fromtimestamp(start)
    end = datetime.datetime.fromtimestamp(end)
    # Fetch the events from MongoDB
    _events = Event.query.filter(Event.timestamp >= start, Event.timestamp <= end)
    # Build the json so FullCalendar will swallow it
    events = []
    for event in _events:
        # Localize the time and get rid of the microseconds
        event_start = UTC.localize(event.timestamp).astimezone(timezone('US/Central')).replace(microsecond=0)
        # Make the event 5 minutes
        event_end = (event_start + datetime.timedelta(minutes=5)).replace(microsecond=0)
        event_dict = {'title' : event.context.description,
                      'id' : event.id,
                      'allDay' : False,
                      'start' : event_start.isoformat(),
                      'end' : event_end.isoformat(),
                      'url' : '/event/{0}'.format(event.id)} # Url for the event detail
        if event.context.status != 0:
            event_dict.update({'color' : 'red'})
        events.append(event_dict)
    return json.dumps(events)
开发者ID:crmccreary,项目名称:LogDashboard,代码行数:26,代码来源:events.py


示例11: handle

 def handle(self, *args, **options):
     if Vaccine.objects.exists() or Pet.objects.exists():
         print('Pet data already loaded...exiting.')
         print(ALREADY_LOADED_ERROR_MESSAGE)
         return
     print("Creating vaccine data")
     for vaccine_name in VACCINES_NAMES:
         vac = Vaccine(name=vaccine_name)
         vac.save()
     print("Loading pet data for pets available for adoption")
     for row in DictReader(open('./pet_data.csv')):
         pet = Pet()
         pet.name = row['Pet']
         pet.submitter = row['Submitter']
         pet.species = row['Species']
         pet.breed = row['Breed']
         pet.description = row['Pet Description']
         pet.sex = row['Sex']
         pet.age = row['Age']
         raw_submission_date = row['submission date']
         submission_date = UTC.localize(
             datetime.strptime(raw_submission_date, DATETIME_FORMAT))
         pet.submission_date = submission_date
         pet.save()
         raw_vaccination_names = row['vaccinations']
         vaccination_names = [name for name in raw_vaccination_names.split('| ') if name]
         for vac_name in vaccination_names:
             vac = Vaccine.objects.get(name=vac_name)
             pet.vaccinations.add(vac)
         pet.save()
开发者ID:UltimoTG,项目名称:wisdompets,代码行数:30,代码来源:load_pet_data.py


示例12: test_timezone

 def test_timezone(self):
     dt = datetime(2009, 11, 10, 23, 0, 0, 123456)
     utc = UTC.localize(dt)
     berlin = timezone('Europe/Berlin').localize(dt)
     eastern = berlin.astimezone(timezone('US/Eastern'))
     data = {
         "points": [
             {"measurement": "A", "fields": {"val": 1},
              "time": 0},
             {"measurement": "A", "fields": {"val": 1},
              "time": "2009-11-10T23:00:00.123456Z"},
             {"measurement": "A", "fields": {"val": 1}, "time": dt},
             {"measurement": "A", "fields": {"val": 1}, "time": utc},
             {"measurement": "A", "fields": {"val": 1}, "time": berlin},
             {"measurement": "A", "fields": {"val": 1}, "time": eastern},
         ]
     }
     self.assertEqual(
         line_protocol.make_lines(data),
         '\n'.join([
             'A val=1i 0',
             'A val=1i 1257894000123456000',
             'A val=1i 1257894000123456000',
             'A val=1i 1257894000123456000',
             'A val=1i 1257890400123456000',
             'A val=1i 1257890400123456000',
         ]) + '\n'
     )
开发者ID:eman,项目名称:influxdb-python,代码行数:28,代码来源:test_line_protocol.py


示例13: _convert_timestamp

def _convert_timestamp(timestamp, precision=None):
    if isinstance(timestamp, Integral):
        return timestamp  # assume precision is correct if timestamp is int

    if isinstance(_get_unicode(timestamp), text_type):
        timestamp = parse(timestamp)

    if isinstance(timestamp, datetime):
        if not timestamp.tzinfo:
            timestamp = UTC.localize(timestamp)

        ns = (timestamp - EPOCH).total_seconds() * 1e9
        if precision is None or precision == 'n':
            return ns
        elif precision == 'u':
            return ns / 1e3
        elif precision == 'ms':
            return ns / 1e6
        elif precision == 's':
            return ns / 1e9
        elif precision == 'm':
            return ns / 1e9 / 60
        elif precision == 'h':
            return ns / 1e9 / 3600

    raise ValueError(timestamp)
开发者ID:bbc,项目名称:influxdb-python,代码行数:26,代码来源:line_protocol.py


示例14: to_mobile_date

 def to_mobile_date(self, cr, uid, model_date):
     user = self.pool.get('res.users').browse(cr, uid, uid)
     local_tz = pytz.timezone(user.partner_id.tz)
     fecha = datetime.strptime(model_date, tools.DEFAULT_SERVER_DATETIME_FORMAT)
     fecha = UTC.localize(fecha, is_dst=False)
     fecha = fecha.astimezone(local_tz)
     return fecha.strftime('%d/%m/%Y %H:%M:%S')
开发者ID:chri5bot,项目名称:GeoOdoo,代码行数:7,代码来源:route.py


示例15: login_patch

def login_patch(auth, username=None, password=None):
    if ((username is None and password is None) or
        (username == 'jane' and password == 'secret')):
        auth._token = '1a2b3c'
        auth._lifespan = 3600
        auth._expires = UTC.localize(datetime.now() + timedelta(hours=1))
        return True
    raise AuthenticationFailed()
开发者ID:AustralianSynchrotron,项目名称:mx-sample-ship,代码行数:8,代码来源:conftest.py


示例16: apply_tzdatabase_timezone

def apply_tzdatabase_timezone(date_time, pytz_string):
    date_time = UTC.localize(date_time)
    usr_timezone = timezone(pytz_string)

    if date_time.tzinfo != usr_timezone:
        date_time = date_time.astimezone(usr_timezone)

    return date_time.replace(tzinfo=None)
开发者ID:sribnis,项目名称:dateparser,代码行数:8,代码来源:utils.py


示例17: localize_timezone

def localize_timezone(datetime, tz=None):
    if not datetime.tzinfo:
        datetime = UTC.localize(datetime)
    if not tz:
        tz = get_timezone()
    if isinstance(tz, basestring):
        tz = timezone(tz)
    return datetime.astimezone(tz)
开发者ID:hasgeek,项目名称:baseframe,代码行数:8,代码来源:__init__.py


示例18: _assert_release_by_creator

 def _assert_release_by_creator(creator, spr):
     release_records = store.find(
         LatestPersonSourcePackageReleaseCache,
         LatestPersonSourcePackageReleaseCache.creator_id == creator.id)
     [record] = list(release_records)
     self.assertEqual(spr.creator, record.creator)
     self.assertIsNone(record.maintainer_id)
     self.assertEqual(
         spr.dateuploaded, UTC.localize(record.dateuploaded))
开发者ID:pombreda,项目名称:UnnaturalCodeFork,代码行数:9,代码来源:test_garbo.py


示例19: apply_timezone

def apply_timezone(date_time, tz_string):
    if not date_time.tzinfo:
        date_time = UTC.localize(date_time)

    new_datetime = apply_dateparser_timezone(date_time, tz_string)

    if not new_datetime:
        new_datetime = apply_tzdatabase_timezone(date_time, tz_string)

    return new_datetime
开发者ID:Sorseg,项目名称:dateparser,代码行数:10,代码来源:__init__.py


示例20: __init__

 def __init__(self, channel_participation, type, source, message, subtype=None):
     self.channel_participation = channel_participation
     self.channel_participation_id = channel_participation.id
     self.type = type
     self.subtype = subtype
     self.source = source
     self.msg = message
     self.stamp = UTC.localize(datetime.datetime.utcnow())
     self.channel_participation.channel.update_last_entry(self.stamp)
     Session.save(self.channel_participation.channel)
开发者ID:UfSoft,项目名称:oil,代码行数:10,代码来源:__init__.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python pytz.timezone函数代码示例发布时间:2022-05-27
下一篇:
Python pytz.tz函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap