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

Python times.to_universal函数代码示例

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

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



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

示例1: on_callback

    def on_callback(self, request):
        if request.method != 'POST':
            request.respond('This hook only supports POST method.')
        else:
            if request.GET.get('secret', [None])[0] != self.bot.config.draftin_secret:
                request.respond('Wrong secret was specified')
            else:
                payload = anyjson.deserialize(request.POST['payload'][0])
                title = payload['name']
                content = payload['content']
                slug = slugify(title)
                created_at = times.to_universal(payload['created_at'])
                updated_at = times.to_universal(payload['updated_at'])
                timezone = self.bot.config.timezone

                with open(os.path.join(
                        self.bot.config.documents_dir,
                        slug + '.md'), 'w') as f:

                    post_content = self.template.format(title=title,
                                                        content=content,
                                                        slug=slug,
                                                        created_at=times.format(created_at, timezone, '%Y-%m-%d %H:%M'),
                                                        updated_at=times.format(updated_at, timezone, '%Y-%m-%d %H:%M'))
                    f.write(post_content.encode('utf-8'))
                    
                try:
                    subprocess.check_output(self.bot.config.update_command,
                                            stderr=subprocess.STDOUT,
                                            shell=True)
                except subprocess.CalledProcessError, e:
                    request.respond(u'I tried to update a blog, but there was an error: ' + e.output.encode('utf-8'))
                else:
                    request.respond('Done, published')
开发者ID:svetlyak40wt,项目名称:thebot-draftin,代码行数:34,代码来源:thebot_draftin.py


示例2: _parse_event

    def _parse_event(self, event):
        starts_at = times.to_universal(event.get('dtstart').dt)
        title_main = event.get('summary')

        title_orig = year = length = None
        tags = []

        match = self.desc_re.match(event.get('description'))
        if match:
            if match.group('title'):
                title_orig = match.group('title').strip()

            year = int(match.group('year'))
            length = int(match.group('min'))

            # TODO scrape tags according to new implementation of tags
            # presented in https://github.com/honzajavorek/zitkino.cz/issues/97
            tags = [self.tags_map.get(t.strip()) for t
                    in match.group('tags').split(',')]

        return Showtime(
            cinema=cinema,
            film_scraped=ScrapedFilm(
                title_main_scraped=title_main,
                title_orig_scraped=title_orig,
                year=year,
                length=length,
            ),
            starts_at=starts_at,
            tags={tag: None for tag in tags if tag},
            url='http://kinonadobraku.cz',
        )
开发者ID:apophys,项目名称:zitkino.cz,代码行数:32,代码来源:letni_kino_na_dobraku.py


示例3: _parse_row

    def _parse_row(self, row, tags=None):
        movie_el = row.cssselect_first('.movie a:not(.tag)')
        url = movie_el.link()
        title = movie_el.text_content()

        date_el = row.cssselect_first('.date').text_content(whitespace=True)
        date, time = re.split(r'[\r\n]+', date_el)

        starts_at = times.to_universal(datetime.datetime.combine(
            parsers.date_cs(date),
            datetime.time(*[int(n) for n in time.split(':')])
        ), 'Europe/Prague')

        tags = self._parse_tags(row, tags)
        details = self._parse_details(url)

        return Showtime(
            cinema=cinema,
            film_scraped=ScrapedFilm(
                title_main_scraped=title,
                url=url,
                **details
            ),
            starts_at=starts_at,
            tags=tags,
            url=self.url,
        )
开发者ID:apophys,项目名称:zitkino.cz,代码行数:27,代码来源:kino_art.py


示例4: date_time_year

def date_time_year(date, time, year=None, tz='Europe/Prague'):
    """Parses strings representing parts of datetime and combines them
    together. Resulting datetime is in UTC.
    """
    dt_string = u'{date} {time} {year}'.format(
        date=date,
        time=time,
        year=year or times.now().year,
    )
    possible_formats = (
        '%d. %m. %H:%M %Y',
        '%d. %m. %H.%M %Y',
    )
    dt = None
    for format in possible_formats:
        try:
            dt = datetime.datetime.strptime(dt_string, format)
        except ValueError:
            pass
        else:
            break
    if dt:
        return times.to_universal(dt, tz)
    else:
        raise ValueError(dt_string)
开发者ID:apophys,项目名称:zitkino.cz,代码行数:25,代码来源:__init__.py


示例5: create_event

def create_event():
    form = EventForm()

    if form.validate_on_submit():
        event = Event()
        with db.transaction as session:
            event.name = form.name.data
            event.venue = form.venue.data
            event.description = form.description.data
            event.user = current_user
            event.starts_at = times.to_universal(form.starts_at.data, current_user.timezone)
            session.add(event)
        with db.transaction:
            event.contacts_invited_ids_str = form.contacts_invited_ids_str.data
        send_email_invites(event)
        return redirect(url_for('facebook_event', id=event.id))

    else:
        # default starts_at
        td = datetime.timedelta(days=1)
        dt = times.to_local(times.now(), current_user.timezone) + td
        dt = datetime.datetime.combine(dt.date(), datetime.time(20, 00, 00))
        form.starts_at.data = dt

    return render_template('create_event.html', form=form)
开发者ID:fdvoracek,项目名称:oleander,代码行数:25,代码来源:events.py


示例6: _parse_date_ranges

    def _parse_date_ranges(self, dates_text):
        """Takes text with date & time information, parses out and generates
        showtimes within date ranges.
        """
        for match in self.range_re.finditer(dates_text):
            # days
            start_day = int(match.group(1))
            end_day = int(match.group(3))

            # months
            start_month = int(match.group(2))
            end_month = int(match.group(4))

            # times
            time_args_list = self._parse_times(match.group(5))

            # years
            start_year = self._determine_year(start_month)
            end_year = self._determine_year(end_month)

            # bounds for rrule
            start = datetime(start_year, start_month, start_day)
            end = datetime(end_year, end_month, end_day)

            # construct and yield datetimes
            for day in rrule.rrule(rrule.DAILY, dtstart=start, until=end):
                for time_args in time_args_list:
                    yield times.to_universal(
                        datetime.combine(day, time(*time_args)),
                        self.tz
                    )
开发者ID:encukou,项目名称:zitkino.cz,代码行数:31,代码来源:kino_lucerna.py


示例7: _parse_time

 def _parse_time(self, el, date):
     """Parses time from given element, combines it with given date and
     returns corresponding datetime object in UTC.
     """
     time = datetime.time(*[int(t) for t in el.text_content().split(':')])
     dt = datetime.datetime.combine(date, time)
     return times.to_universal(dt, timezone='Europe/Prague')
开发者ID:apophys,项目名称:zitkino.cz,代码行数:7,代码来源:kino_scala.py


示例8: test_to_universal_without_tzinfo

    def test_to_universal_without_tzinfo(self):
        """Convert local dates without timezone info to universal date"""

        # Same as above, but with tzinfo stripped off (as if a NY and Amsterdam
        # user used datetime.now())
        ny_time = self.time_in_ny.replace(tzinfo=None)
        ams_time = self.time_in_ams.replace(tzinfo=None)

        # When time has no tzinfo attached, it should be specified explicitly
        est = 'EST'
        self.assertEquals(times.to_universal(ny_time, est),
                          self.sometime_univ)

        # ...or simply with a string
        self.assertEquals(times.to_universal(ams_time, 'Europe/Amsterdam'),
                          self.sometime_univ)
开发者ID:gionniboy,项目名称:times,代码行数:16,代码来源:test_times.py


示例9: test_to_universal_with_unix_timestamp

 def test_to_universal_with_unix_timestamp(self):
     """Convert UNIX timestamps to universal date"""
     unix_time = 1328257004.456  # as returned by time.time()
     self.assertEquals(
         times.to_universal(unix_time),
         datetime(2012, 2, 3, 8, 16, 44, 456000)
     )
开发者ID:Mondego,项目名称:pyreco,代码行数:7,代码来源:allPythonContent.py


示例10: _parse_event

    def _parse_event(self, event):
        starts_at = times.to_universal(event.get('dtstart').dt)
        title_main = event.get('summary')
        titles = [title_main]

        title_orig = year = length = None
        tags = []

        match = self.desc_re.match(event.get('description'))
        if match:
            if match.group('title'):
                title_orig = match.group('title').strip()
                titles.append(title_orig)

            year = int(match.group('year'))
            length = int(match.group('min'))

            tags = [self.tags_map.get(t.strip()) for t
                    in match.group('tags').split(',')]

        return Showtime(
            cinema=cinema,
            film_scraped=ScrapedFilm(
                title_main=title_main,
                title_orig=title_orig,
                titles=titles,
                year=year,
                length=length,
            ),
            starts_at=starts_at,
            tags=tags,
            price=self.price,
        )
开发者ID:volmutJ,项目名称:zitkino.cz,代码行数:33,代码来源:letni_kino_na_dobraku.py


示例11: _parse_standalone_dates

    def _parse_standalone_dates(self, dates_text):
        """Takes text with date & time information, parses out and generates
        standalone showtimes.
        """
        dates_text = self.range_re.sub('', dates_text)
        for match in self.standalone_re.finditer(dates_text):
            date_args_list = []

            # standalone date
            date_args_list.append(map(int, [
                self._determine_year(match.group(2)),  # year
                match.group(2),  # month
                match.group(1),  # day
            ]))

            # date+date, let's process the second one
            if match.group(3):
                date_args_list.append(map(int, [
                    self._determine_year(match.group(5)),  # year
                    match.group(5),  # month
                    match.group(4),  # day
                ]))

            # parse times
            time_args_list = self._parse_times(match.group(6))

            # construct and yield datetimes
            for date_args in date_args_list:
                for time_args in time_args_list:
                    yield times.to_universal(
                        datetime(*(date_args + time_args)),
                        self.tz
                    )
开发者ID:encukou,项目名称:zitkino.cz,代码行数:33,代码来源:kino_lucerna.py


示例12: test_to_universal_with_tzinfo

    def test_to_universal_with_tzinfo(self):  # noqa
        """Convert local dates with timezone info to universal date"""
        ny_time = self.time_in_ny
        ams_time = self.time_in_ams

        self.assertEquals(times.to_universal(ny_time),
                          self.sometime_univ)
        self.assertEquals(times.to_universal(ams_time),
                          self.sometime_univ)

        self.assertEquals(ny_time.hour, 6)
        self.assertEquals(times.to_universal(ny_time).hour, 11)

        self.assertEquals(ams_time.hour, 12)
        self.assertEquals(times.to_universal(ams_time).hour, 11)

        # Test alias from_local, too
        self.assertEquals(times.from_local(ny_time), self.sometime_univ)
开发者ID:gionniboy,项目名称:times,代码行数:18,代码来源:test_times.py


示例13: calculate_score

 def calculate_score(self):
     now     = times.now()
     then    = times.to_universal(self.created)
     hour_age= ceil((now-then).total_seconds()/60/60)
     gravity = 1.8
     self.calculated_score = (self.love_count-1)/pow((hour_age+2), gravity)
     self.save()
     print "%s -- %s -- %s" % (self.calculated_score, hour_age, self.title)
     return (self.love_count-1) / pow((hour_age+2), gravity)
开发者ID:bmelton,项目名称:djig,代码行数:9,代码来源:models.py


示例14: test_local_time_with_tzinfo_to_universal

    def test_local_time_with_tzinfo_to_universal(self):
        """Convert local dates with timezone info to universal date"""
        ny_time = self.sometime_in_newyork
        ams_time = self.sometime_in_amsterdam

        self.assertEquals(
                times.to_universal(ny_time),
                self.sometime_univ)
        self.assertEquals(
                times.to_universal(ams_time),
                self.sometime_univ)

        self.assertEquals(ny_time.hour, 6)
        self.assertEquals(
                times.to_universal(ny_time).hour, 11)

        self.assertEquals(ams_time.hour, 12)
        self.assertEquals(
                times.to_universal(ams_time).hour, 11)
开发者ID:mvanveen,项目名称:times,代码行数:19,代码来源:test_times.py


示例15: __call__

    def __call__(self):
        resp = self.session.get(self.url)
        html = parsers.html(resp.content, base_url=resp.url)

        for event in html.cssselect('.event'):
            header = event.cssselect_first('h2')

            url = header.link()
            title = header.text_content()

            title_parts = title.split('/')
            if len(title_parts) == 2:
                # naive, but for now good enough
                title_main, title_orig = title_parts
            else:
                title_main = title
                title_orig = None

            details = event.cssselect_first('.descshort').text_content()
            cat = event.cssselect_first('.title-cat').text_content().lower()

            tags = []
            for regexp, tag in self.tag_re:
                if regexp.search(title_main):
                    tags.append(tag)
                    title_main = regexp.sub('', title_main).strip()
                if title_orig and regexp.search(title_orig):
                    tags.append(tag)
                    title_orig = regexp.sub('', title_orig).strip()
                if regexp.search(details):
                    tags.append(tag)
            if cat != 'filmy':
                tags.append(cat)

            d = parsers.date_cs(
                event.cssselect_first('.nextdate strong').text
            )

            t = event.cssselect_first('.nextdate .evttime').text_content()
            t = time(*map(int, t.split(':')))

            starts_at = times.to_universal(datetime.combine(d, t), self.tz)

            yield Showtime(
                cinema=cinema,
                film_scraped=ScrapedFilm(
                    title_main_scraped=title_main,
                    title_orig=title_orig or None,
                ),
                starts_at=starts_at,
                url=url,
                url_booking=self.url_booking,
                tags={tag: None for tag in tags},
            )
开发者ID:apophys,项目名称:zitkino.cz,代码行数:54,代码来源:kino_lucerna.py


示例16: str_to_utc

def str_to_utc(s, format_str='%Y-%m-%d %H:%M:%S',
               timezone=settings.TIME_ZONE, default=None):
    """本地日期字符串转化为 UTC datetime"""
    try:
        d = str_to_local(s, format_str)
        return times.to_universal(d, timezone).replace(tzinfo=pytz.UTC)
    except:
        if default:
            return default
        else:
            raise
开发者ID:starer93,项目名称:chendian-plus,代码行数:11,代码来源:utils.py


示例17: test_persistence_of_typical_jobs

    def test_persistence_of_typical_jobs(self):
        """Storing typical jobs."""
        job = Job.create(func=some_calculation, args=(3, 4), kwargs=dict(z=2))
        job.save()

        expected_date = strip_milliseconds(job.created_at)
        stored_date = self.testconn.hget(job.key, "created_at")
        self.assertEquals(times.to_universal(stored_date), expected_date)

        # ... and no other keys are stored
        self.assertItemsEqual(self.testconn.hkeys(job.key), ["created_at", "data", "description"])
开发者ID:yaniv-aknin,项目名称:rq,代码行数:11,代码来源:test_job.py


示例18: test_persistence_of_empty_jobs

    def test_persistence_of_empty_jobs(self):  # noqa
        """Storing empty jobs."""
        job = Job()
        job.save()

        expected_date = strip_milliseconds(job.created_at)
        stored_date = self.testconn.hget(job.key, "created_at")
        self.assertEquals(times.to_universal(stored_date), expected_date)

        # ... and no other keys are stored
        self.assertItemsEqual(self.testconn.hkeys(job.key), ["created_at"])
开发者ID:yaniv-aknin,项目名称:rq,代码行数:11,代码来源:test_job.py


示例19: _parse_entry

    def _parse_entry(self, entry):
        try:
            description = next(
                line for line
                in entry.text_content(whitespace=True).splitlines()
                if self.length_re.search(line)
            )
        except StopIteration:
            return None  # it's not a film

        date_el = entry.cssselect_first('h4 span')
        date = datetime.datetime(*reversed(
            [int(n) for n in date_el.text_content().split('.')]
        ))

        time_el = entry.cssselect_first('.start')
        time_match = self.time_re.search(time_el.text_content())
        time = datetime.time(
            int(time_match.group(1)),
            int(time_match.group(2)),
        )

        starts_at = times.to_universal(
            datetime.datetime.combine(date, time),
            'Europe/Prague'
        )
        title = date_el.tail

        tags = {}
        detail_data = {}

        details = [detail.strip() for detail in description.split(',')]
        for detail in details:
            if self.year_re.match(detail):
                detail_data['year'] = int(detail)

            match = self.length_re.match(detail)
            if match:
                detail_data['length'] = int(match.group(1))

            if 'tit.' in detail or 'titulky' in detail or 'dabing' in detail:
                tags[detail] = None

        return Showtime(
            cinema=cinema,
            film_scraped=ScrapedFilm(
                title_main_scraped=title,
                **detail_data
            ),
            starts_at=starts_at,
            tags=tags,
            url=self.url,
        )
开发者ID:apophys,项目名称:zitkino.cz,代码行数:53,代码来源:kinokavarna.py


示例20: timezone

 def timezone(self, zone):
     """
     Change the time zone and affect the current moment's time. Note, a
     locality must already be set.
     """
     date = self._date
     try:
         date = times.to_local(times.to_universal(date), zone)
     except:
         date = times.to_local(date, zone)
     finally:
         self._date = date
     return self
开发者ID:zachwill,项目名称:moment,代码行数:13,代码来源:core.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python timeseries.TimeSeries类代码示例发布时间:2022-05-27
下一篇:
Python times.now函数代码示例发布时间: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