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

Python datefmt.parse_date函数代码示例

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

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



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

示例1: test_parse_date_dst

 def test_parse_date_dst(self):
     tz = datefmt.get_timezone('Europe/Zurich')
     t_utc = datetime.datetime(2009, 8, 1, 10, 0, 0, 0, datefmt.utc)
     self.assertEqual(t_utc,
             datefmt.parse_date('2009-08-01T12:00:00', tz))
     self.assertEqual(t_utc,
             datefmt.parse_date('2009-08-01 12:00:00', tz))
开发者ID:trac-ja,项目名称:trac-ja,代码行数:7,代码来源:datefmt.py


示例2: test_parse_date_offset

 def test_parse_date_offset(self):
     t_utc = datetime.datetime(2009, 12, 1, 11, 0, 0, 0, datefmt.utc)
     self.assertEqual(t_utc,
                      datefmt.parse_date('2009-12-01T11:00:00Z'))
     self.assertEqual(t_utc,
                      datefmt.parse_date('2009-12-01T11:00:00+00:00'))
     self.assertEqual(t_utc,
                      datefmt.parse_date('2009-12-01T11:00:00-00:00'))
     self.assertEqual(t_utc,
                      datefmt.parse_date('2009-12-01T09:00:00-02:00'))
     self.assertEqual(t_utc,
                      datefmt.parse_date('2009-12-01T11:30:00+00:30'))
开发者ID:trac-ja,项目名称:trac-ja,代码行数:12,代码来源:datefmt.py


示例3: test_i18n_parse_date_datetime_meridiem

        def test_i18n_parse_date_datetime_meridiem(self):
            tz = datefmt.timezone('GMT +2:00')
            expected_am = datetime.datetime(2011, 2, 22, 0, 45, 56, 0, tz)
            expected_pm = datetime.datetime(2011, 2, 22, 12, 45, 56, 0, tz)
            en_US = Locale.parse('en_US')
            zh_CN = Locale.parse('zh_CN')

            self.assertEqual(expected_am,
                             datefmt.parse_date('Feb 22, 2011 0:45:56 AM', tz,
                                                en_US))
            self.assertEqual(expected_am,
                             datefmt.parse_date('Feb 22, 2011 12:45:56 AM', tz,
                                                en_US))
            self.assertEqual(expected_am,
                             datefmt.parse_date(u'2011-2-22 上午0:45:56', tz,
                                                zh_CN))
            self.assertEqual(expected_am,
                             datefmt.parse_date(u'2011-2-22 上午12:45:56', tz,
                                                zh_CN))

            self.assertEqual(expected_pm,
                             datefmt.parse_date('Feb 22, 2011 0:45:56 PM', tz,
                                                en_US))
            self.assertEqual(expected_pm,
                             datefmt.parse_date('Feb 22, 2011 12:45:56 PM', tz,
                                                en_US))
            self.assertEqual(expected_pm,
                             datefmt.parse_date(u'2011-2-22 下午0:45:56', tz,
                                                zh_CN))
            self.assertEqual(expected_pm,
                             datefmt.parse_date(u'2011-2-22 下午12:45:56', tz,
                                                zh_CN))
开发者ID:trac-ja,项目名称:trac-ja,代码行数:32,代码来源:datefmt.py


示例4: valid_date_format

    def valid_date_format(self):
        """
        Returns a boolean to indicate if the start and end dates are ISO-8601 format.
        We pass these respective values to the trac utils parse_date function,
        which will raise a ValueError exception if the date format of the
        string is not ISO-8601 compliant.
        """

        for date in (self['start'], self['end']):
            try:
                parse_date(date)
            except TracError:
                return False

        return True
开发者ID:CGI-define-and-primeportal,项目名称:trac-plugin-projectmessage,代码行数:15,代码来源:models.py


示例5: _parse_args

 def _parse_args(self, req):
     start = req.args.get('start')
     if start:
         start = datefmt.parse_date(start, tzinfo=req.tz)
     end = req.args.get('end')
     if end:
         end = datefmt.parse_date(end, tzinfo=req.tz)
     duration = req.args.get('duration')
     if duration:
         try:
             duration = int(duration)
         except ValueError:
             duration = None
             
     return start, end, duration
开发者ID:djangsters,项目名称:agilo,代码行数:15,代码来源:admin.py


示例6: _init_defaults

 def _init_defaults(self):
     for field in self.fields:
         default = None
         if field["name"] in self.protected_fields:
             # Ignore for new - only change through workflow
             pass
         elif not field.get("custom"):
             default = self.env.config.get("ticket", "default_" + field["name"])
         else:
             default = field.get("value")
             options = field.get("options")
             if default and options and default not in options:
                 try:
                     default = options[int(default)]
                 except (ValueError, IndexError):
                     self.env.log.warning(
                         'Invalid default value "%s" ' 'for custom field "%s"' % (default, field["name"])
                     )
             if default and field.get("type") == "time":
                 try:
                     default = parse_date(default, hint=field.get("format"))
                 except TracError, e:
                     self.env.log.warning(
                         'Invalid default value "%s" ' 'for custom field "%s": %s' % (default, field["name"], e)
                     )
                     default = None
         if default:
             self.values.setdefault(field["name"], default)
开发者ID:nextview,项目名称:medicticket,代码行数:28,代码来源:model.py


示例7: generate_remaining_time_data

    def generate_remaining_time_data(self, task, start_date, end_date=None):
        def create_burndown_data_change(remaining_time, when):
            task[Key.REMAINING_TIME] = str(remaining_time)
            task.save_changes(author=task[Key.OWNER], comment='Updated time...', when=when)

            # Reset time of the last burndown data change
            changes = BurndownDataChangeModelManager(self.env).select(limit=1, order_by=['-id'])
            last_burndown_change = changes[0]
            last_burndown_change.update_values(when=when).save()

        if task.get_type() != Type.TASK:
            return
        if not end_date:
            end_date = parse_date('now')

        remaining_time = randint(4,12)
        create_burndown_data_change(remaining_time, start_date)

        if not task.has_owner:
            return
        when = start_date + timedelta(hours=randint(4,16))
        while when < end_date:
            remaining_time += randint(-3,0)
            # if the remaining time is set to 0, the task will be closed!
            if remaining_time <= 0:
                remaining_time = 1

            create_burndown_data_change(remaining_time, when)
            when += timedelta(hours=randint(4,16))
开发者ID:djangsters,项目名称:agilo,代码行数:29,代码来源:test_env_helper.py


示例8: insert

    def insert(self):
        """
        Insert a new project message row into the database table.

        Before any insert transaction is committed, we validate the data.

        After a successful insert, appropriate caches are invalidated.
        """

        if self.validate():
            args = []
            for key in self.message_keys:
                if key == 'groups':
                    args.append(json.dumps(self[key]))
                elif key in ['start', 'end']:
                    args.append(to_utimestamp(parse_date(self[key])))
                else:
                    args.append(self[key])

            @self.env.with_transaction()
            def do_insert(db):
                cursor = db.cursor()
                self.env.log.debug("Creating new projet message - %s", self['name'])
                cursor.execute("""INSERT INTO project_message (name, message, 
                                    button, mode, groups, 
                                    start, "end", author, created_at)
                                  VALUES (%s, %s, %s, %s, %s, 
                                    %s, %s, %s, %s)
                                """, args)

        del self._get_all_messages
开发者ID:CGI-define-and-primeportal,项目名称:trac-plugin-projectmessage,代码行数:31,代码来源:models.py


示例9: test_parse_date_usec

 def test_parse_date_usec(self):
     tz = datefmt.get_timezone('GMT +1:00')
     t_utc = datetime.datetime(2009, 12, 1, 11, 0, 0, 98765, datefmt.utc)
     self.assertEqual(t_utc,
                      datefmt.parse_date('2009-12-01T12:00:00.098765', tz))
     self.assertEqual(t_utc,
                      datefmt.parse_date('2009-12-01T12:00:00,098765', tz))
     self.assertEqual(datetime.datetime(2009, 12, 1, 11, 0, 0, 98700,
                                        datefmt.utc),
                      datefmt.parse_date('2009-12-01T12:00:00.0987', tz))
     self.assertEqual(datetime.datetime(2009, 12, 1, 11, 0, 0, 90000,
                                        datefmt.utc),
                      datefmt.parse_date('2009-12-01T12:00:00.09', tz))
     self.assertEqual(datetime.datetime(2009, 12, 1, 11, 0, 0, 0,
                                        datefmt.utc),
                      datefmt.parse_date('2009-12-01T12:00:00.0', tz))
开发者ID:trac-ja,项目名称:trac-ja,代码行数:16,代码来源:datefmt.py


示例10: testSprintSelect

 def testSprintSelect(self):
     """Test the Sprint select function"""
     self.manager.create(name="Test Sprint 1",
                               start=self.start,
                               end=self.end)
     self.manager.create(name="Test Sprint 2",
                               start=self.start,
                               end=self.end)
     self.manager.create(name="Test Sprint 3",
                               start=parse_date("2008-06-10"),
                               end=parse_date("2008-06-30"))
     # Now test the select
     sprints = self.manager.select(criteria={'end': '> %d' % to_timestamp(now())})
     self.assert_equals(len(sprints), 2)
     sprints = self.manager.select()
     self.assert_equals(len(sprints), 3)
开发者ID:djangsters,项目名称:agilo,代码行数:16,代码来源:sprint_test.py


示例11: testSprintClosedAndIsCurrentlyRunning

 def testSprintClosedAndIsCurrentlyRunning(self):
     """Tests the is_closed and is_started"""
     start = now() - timedelta(days=3) # no risk to get a weekend
     s = self.teh.create_sprint("Test", start=start)
     self.assert_true(s.is_currently_running)
     self.assert_false(s.is_closed)
     s.start += timedelta(days=5) # Move 5 to make sure that we will overcome also a normalization over a weekend
     self.assert_false(s.is_currently_running, "%s <= %s  < %s" % \
                      (s.start, start, s.end))
     self.assert_false(s.is_closed)
     
     # check functions for an old, closed sprint
     s.start = parse_date("2008-01-01")
     s.end = parse_date("2008-01-31")
     self.assert_false(s.is_currently_running)
     self.assert_true(s.is_closed)
开发者ID:djangsters,项目名称:agilo,代码行数:16,代码来源:sprint_test.py


示例12: _validate_add

    def _validate_add(self, req):
        ty = req.args.get('reminder_type')

        if ty == 'interval':
            try:
                req.args['interval'] = int(req.args.get('interval', '').strip())
                if req.args['interval'] <= 0:
                    add_warning(req, "Nonpositive interval value.")
                    return False
            except ValueError:
                add_warning(req, "Invalid or missing interval value.")
                return False

            if req.args.get('unit') not in ['day', 'week', 'month', 'year']:
                add_warning(req, "Please select interval unit.")
                return False

        elif ty == 'date':
            try:
                time = clear_time(parse_date(req.args.get('date', '').strip()))
                req.args['date'] = format_date(time)
                now = to_datetime(None)
                if time <= now:
                    add_warning(req, "Date value not in the future.")
                    return False
            except TracError:
                add_warning(req, "Invalid or missing date value.")
                return False

        else:
            add_warning(req, "Please select type.")
            return False

        return True
开发者ID:trac-hacks,项目名称:trac-ticketreminder,代码行数:34,代码来源:api.py


示例13: _process_add

    def _process_add(self, req, ticket):
        if req.method == "POST" and self._validate_add(req):
            if req.args.get('reminder_type') == 'interval':
                time = clear_time(to_datetime(None))
                delta = _time_intervals[req.args.get('unit')](req.args.get('interval'))
                time += delta
                time = to_utimestamp(time)
            else:
                time = to_utimestamp(parse_date(req.args.get('date')))
            origin = to_utimestamp(to_datetime(None))

            self.env.db_transaction("""
                INSERT INTO ticketreminder
                 (ticket, time, author, origin, reminded, description)
                VALUES (%s, %s, %s, %s, 0, %s)
                """, (ticket.id, time, get_reporter_id(req, 'author'),
                      origin, req.args.get('description')))

            add_notice(req, "Reminder has been added.")
            req.redirect(get_resource_url(self.env, ticket.resource, req.href) + "#reminders")

        add_script(req, 'ticketreminder/js/ticketreminder.js')

        data = {
            'ticket': ticket,
            'date_hint': get_date_format_hint(),
        }

        return ("ticket_reminder_add.html", data, None)
开发者ID:trac-hacks,项目名称:trac-ticketreminder,代码行数:29,代码来源:api.py


示例14: testCapacityHours

 def testCapacityHours(self):
     """Test the get_capacity_hours() method"""
     test_team = self.tm.create(name="Team#1")
     self.assert_true(test_team.exists)
     test_members = (self.tmm.create(name="Member#1", team=test_team),
                     self.tmm.create(name="Member#2", team=test_team, 
                                           default_capacity=[4,4,4,0,0,0,0]),
                     self.tmm.create(name="Member#3", team=test_team, 
                                           default_capacity=[0,0,0,2,2,0,0]))
     for tm in test_members:
         self.assert_not_none(tm.team)
         self.assert_equals(test_team, tm.team)
     
     # test the default constructor
     start_date = parse_date("2008-09-08T08:00:00")
     test_sprint =  self.teh.create_sprint(name="TestSprint", start=start_date, 
                                           duration=10)
     
     # test save and restore
     for member in test_members:
         self.assert_true(self.tmm.save(member))
     
     test_sprint.team = test_team
     test_sprint.save()
     
     weekly_hours = (5 * 6) + (4 + 4 + 4) + (2 + 2)
     self.assert_equals(weekly_hours, test_team.capacity().default_hours_of_capacity_per_week())
     
     sprint_hours = 2 * weekly_hours
     actual = test_team.capacity().hourly_capacities_in_sprint(test_sprint)
     capacity = sum(map(lambda each: each.capacity, actual))
     self.assert_almost_equals(sprint_hours, capacity, max_delta=.01)
开发者ID:djangsters,项目名称:agilo,代码行数:32,代码来源:team_test.py


示例15: _init_defaults

 def _init_defaults(self):
     for field in self.fields:
         default = None
         if field['name'] in self.protected_fields:
             # Ignore for new - only change through workflow
             pass
         elif not field.get('custom'):
             default = self.env.config.get('ticket',
                                           'default_' + field['name'])
         else:
             default = field.get('value')
             options = field.get('options')
             if default and options and default not in options:
                 try:
                     default = options[int(default)]
                 except (ValueError, IndexError):
                     self.env.log.warning('Invalid default value "%s" '
                                          'for custom field "%s"'
                                          % (default, field['name']))
             if default and field.get('type') == 'time':
                 try:
                     default = parse_date(default,
                                          hint=field.get('format'))
                 except TracError, e:
                     self.env.log.warning('Invalid default value "%s" '
                                          'for custom field "%s": %s'
                                          % (default, field['name'], e))
                     default = None
         if default:
             self.values.setdefault(field['name'], default)
开发者ID:dafrito,项目名称:trac-mirror,代码行数:30,代码来源:model.py


示例16: _do_add

 def _do_add(self, name, due=None):
     milestone = model.Milestone(self.env)
     milestone.name = name
     if due is not None:
         milestone.due = parse_date(due, hint='datetime',
                                    locale=get_console_locale(self.env))
     milestone.insert()
开发者ID:exocad,项目名称:exotrac,代码行数:7,代码来源:admin.py


示例17: expand_macro

    def expand_macro(self, formatter, name, content):
        offset = +1
        label = None
        if content is not None:
            if ',' in content:
                offset, label = content.split(',', 1)
            elif content and content[0] in '+-':
                offset = content
            else:
                label = content
            try:
                offset = int(offset)
            except ValueError:
                offset = 0
        mp = MyPageModule(self.env)
        base = mp.get_mypage_base(formatter.perm.username)
        all_mypages = mp.get_all_mypages(base)
        r = formatter.resource
        if r.realm == 'wiki' and r.id.startswith(base):
            mypage = r.id
        else:
            tzinfo = getattr(formatter.context.req, 'tz', None)
            now = datetime.now(tzinfo or localtz)
            today = format_date(now, 'iso8601', tzinfo)
            mypage = '/'.join([base, today])
        selected = base
        idx = bisect(all_mypages, mypage)

        # adjust to actual position if mypage exists
        if 0 <= idx - 1 < len(all_mypages) and all_mypages[idx -1] == mypage:
            idx -= 1
        self.log.debug("Reference is %s, pos %d in %r",
                       mypage, idx, all_mypages)

        # Special cases: at the beginning or at the end, the
        # predecessors resp. successors are "missing"
        missing = False
        if idx >= len(all_mypages) - 1 and offset > 0:
            missing, tooltip = True, _("(at the end)")
        elif idx < 1 and offset < 0:
            missing, tooltip = True, _("(at the beginning)")
        if missing:
            if not label:
                label, tooltip = tooltip, None
            return tag.a(label, title=tooltip, class_='missing')

        # Link to the targeted `MyPage` page
        idx += offset
        selected = all_mypages[max(0, min(idx, len(all_mypages) - 1))]
        self.log.debug("With offset %d, going to %d (adjusted to %d)",
                       offset, idx, max(0, min(idx, len(all_mypages) - 1)))
        selected_day = selected.split('/')[-1]
        try:
            tooltip = _("MyPage for %(day)s",
                        day=format_date(parse_date(selected_day)))
        except TracError:
            tooltip = _("non-day page '%(special)'", special=selected_day)
        return tag.a(label if label is not None else selected, title=tooltip,
                     href=formatter.href.wiki(selected))
开发者ID:cboos,项目名称:trac-mypage-plugin,代码行数:59,代码来源:mypage.py


示例18: set_date

 def set_date(name, attr_name = None):
     val = attributes.get(name)
     if val is None:
         return
     val = val and parse_date(val, tzinfo=req.tz) or None
     if attr_name is not None:
         setattr(milestone, attr_name, val)
     milestone.ticket[name] = val and str(to_timestamp(val))
开发者ID:esogs,项目名称:IttecoTracPlugin,代码行数:8,代码来源:roadmap.py


示例19: _date_convert

 def _date_convert(self, date_str):
     try:
         locale = get_console_locale(self._env)
         return to_timestamp(parse_date(date_str, hint='date',
                                        locale=locale))
     except Exception as excpt:
         self._env.log.exception(excpt)
         raise EmptyRangeError(excpt.message)
开发者ID:ebouaziz,项目名称:TracRevTreePlugin,代码行数:8,代码来源:web_ui.py


示例20: test_parse_date_across_dst_boundary

 def test_parse_date_across_dst_boundary(self):
     tz = datefmt.get_timezone('Europe/Zurich')
     # DST start - 31 March, 02:00
     format = '%Y-%m-%d %H:%M:%S %Z%z'
     expected = '2002-03-31 03:30:00 CEST+0200'
     # iso8601
     t = datefmt.parse_date('2002-03-31T02:30:00', tz)
     self.assertEqual(expected, t.strftime(format))
     # strptime
     t = datetime.datetime(2002, 3, 31, 2, 30)
     t = datefmt.parse_date(t.strftime('%x %X'), tz)
     self.assertEqual(expected, t.strftime(format))
     # i18n datetime
     if Locale:
         en_US = Locale.parse('en_US')
         t = datefmt.parse_date('Mar 31, 2002 02:30', tz, en_US)
         self.assertEqual(expected, t.strftime(format))
开发者ID:trac-ja,项目名称:trac-ja,代码行数:17,代码来源:datefmt.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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