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

Python calendar.Calendar类代码示例

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

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



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

示例1: getTimezone

    def getTimezone(self, tzid):
        """
        Generate a PyCalendar containing the requested timezone.
        """
        # We will just use our existing TimezoneCache here
        calendar = Calendar()
        try:
            vtz = readVTZ(tzid)
            calendar.addComponent(vtz.getComponents()[0].duplicate())
        except TimezoneException:

            # Check if an alias exists and create data for that
            if tzid in self.aliases:
                try:
                    vtz = readVTZ(self.aliases[tzid])
                except TimezoneException:
                    log.error("Failed to find timezone data for alias: %s" % (tzid,))
                    return None
                else:
                    vtz = vtz.duplicate()
                    vtz.getComponents()[0].getProperties("TZID")[0].setValue(tzid)
                    addVTZ(tzid, vtz)
                    calendar.addComponent(vtz.getComponents()[0].duplicate())
            else:
                log.error("Failed to find timezone data for: %s" % (tzid,))
                return None

        return calendar
开发者ID:redtailtech,项目名称:calendarserver,代码行数:28,代码来源:timezonestdservice.py


示例2: generateZoneinfoFiles

    def generateZoneinfoFiles(self, outputdir, minYear, maxYear=2018, links=True, windowsAliases=None, filterzones=None):

        # Empty current directory
        try:
            for root, dirs, files in os.walk(outputdir, topdown=False):
                for name in files:
                    os.remove(os.path.join(root, name))
                for name in dirs:
                    os.rmdir(os.path.join(root, name))
        except OSError:
            pass

        for zone in self.zones.itervalues():
            if filterzones and zone.name not in filterzones:
                continue
            cal = Calendar()
            vtz = zone.vtimezone(cal, self.rules, minYear, maxYear)
            cal.addComponent(vtz)

            icsdata = cal.getText()
            fpath = os.path.join(outputdir, zone.name + ".ics")
            if not os.path.exists(os.path.dirname(fpath)):
                os.makedirs(os.path.dirname(fpath))
            with open(fpath, "w") as f:
                f.write(icsdata)
            if self.verbose:
                print("Write path: %s" % (fpath,))

        if links:
            if windowsAliases is not None:
                self.parseWindowsAliases(windowsAliases)

            link_list = []
            for linkTo, linkFrom in sorted(self.links.iteritems(), key=lambda x: x[0]):

                # Check for existing output file
                fromPath = os.path.join(outputdir, linkFrom + ".ics")
                if not os.path.exists(fromPath):
                    print("Missing link from: %s to %s" % (linkFrom, linkTo,))
                    continue

                with open(fromPath) as f:
                    icsdata = f.read()
                icsdata = icsdata.replace(linkFrom, linkTo)

                toPath = os.path.join(outputdir, linkTo + ".ics")
                if not os.path.exists(os.path.dirname(toPath)):
                    os.makedirs(os.path.dirname(toPath))
                with open(toPath, "w") as f:
                    f.write(icsdata)
                if self.verbose:
                    print("Write link: %s" % (linkTo,))

                link_list.append("%s\t%s" % (linkTo, linkFrom,))

            # Generate link mapping file
            linkPath = os.path.join(outputdir, "links.txt")
            with open(linkPath, "w") as f:
                f.write("\n".join(link_list))
开发者ID:eventable,项目名称:PyCalendar,代码行数:59,代码来源:tzconvert.py


示例3: loadCalendar

def loadCalendar(file, verbose):

    cal = Calendar()
    if verbose:
        print "Parsing calendar data: %s" % (file,)
    with open(file, "r") as fin:
        try:
            cal.parse(fin)
        except InvalidData, e:
            print "Failed to parse bad data: %s" % (e.mData,)
            raise
开发者ID:eventable,项目名称:PyCalendar,代码行数:11,代码来源:tzdump.py


示例4: _doTest

                    def _doTest():
                        result = None
                        if test[0] == '@':
                            if '=' in test:
                                attr, value = test[1:].split('=')
                                value = value[1:-1]
                            else:
                                attr = test[1:]
                                value = None
                            if attr not in node.keys():
                                result = "        Missing attribute returned in XML for %s\n" % (path,)
                            if value is not None and node.get(attr) != value:
                                result = "        Incorrect attribute value returned in XML for %s\n" % (path,)
                        elif test[0] == '=':
                            if node.text != test[1:]:
                                result = "        Incorrect value returned in XML for %s\n" % (path,)
                        elif test[0] == '!':
                            if node.text == test[1:]:
                                result = "        Incorrect value returned in XML for %s\n" % (path,)
                        elif test[0] == '*':
                            if node.text is None or node.text.find(test[1:]) == -1:
                                result = "        Incorrect value returned in XML for %s\n" % (path,)
                        elif test[0] == '$':
                            if node.text is None or node.text.find(test[1:]) != -1:
                                result = "        Incorrect value returned in XML for %s\n" % (path,)
                        elif test[0] == '+':
                            if node.text is None or not node.text.startswith(test[1:]):
                                result = "        Incorrect value returned in XML for %s\n" % (path,)
                        elif test[0] == '^':
                            if "=" in test:
                                element, value = test[1:].split("=", 1)
                            else:
                                element = test[1:]
                                value = None
                            for child in node.getchildren():
                                if child.tag == element and (value is None or child.text == value):
                                    break
                            else:
                                result = "        Missing child returned in XML for %s\n" % (path,)

                        # Try to parse as iCalendar
                        elif test == 'icalendar':
                            try:
                                Calendar.parseText(node.text)
                            except:
                                result = "        Incorrect value returned in iCalendar for %s\n" % (path,)

                        # Try to parse as JSON
                        elif test == 'json':
                            try:
                                json.loads(node.text)
                            except:
                                result = "        Incorrect value returned in XML for %s\n" % (path,)
                        return result
开发者ID:agx,项目名称:caldav-tester-packaging,代码行数:54,代码来源:xmlElementMatch.py


示例5: _doRoundtrip

        def _doRoundtrip(caldata, jcaldata):
            cal1 = Calendar.parseText(caldata)
            test1 = cal1.getText()

            cal2 = Calendar.parseJSONData(jcaldata)
            test2 = cal2.getText()

            self.assertEqual(
                test1,
                test2,
                "\n".join(difflib.unified_diff(str(test1).splitlines(), test2.splitlines()))
            )
开发者ID:eventable,项目名称:PyCalendar,代码行数:12,代码来源:test_json.py


示例6: getTimezoneInCalendar

    def getTimezoneInCalendar(tzid):
        """
        Return a VTIMEZONE inside a valid VCALENDAR
        """

        tz = TimezoneDatabase.getTimezone(tzid)
        if tz is not None:
            from pycalendar.icalendar.calendar import Calendar
            cal = Calendar()
            cal.addComponent(tz.duplicate(cal))
            return cal
        else:
            return None
开发者ID:eventable,项目名称:PyCalendar,代码行数:13,代码来源:timezonedb.py


示例7: _doRoundtrip

        def _doRoundtrip(caldata, resultdata=None):
            test1 = resultdata if resultdata is not None else caldata

            cal = Calendar()
            cal.parse(StringIO.StringIO(caldata))

            test2 = cal.getTextXML()

            self.assertEqual(
                test1,
                test2,
                "\n".join(difflib.unified_diff(str(test1).splitlines(), test2.splitlines()))
            )
开发者ID:eventable,项目名称:PyCalendar,代码行数:13,代码来源:test_xml.py


示例8: vtimezones

    def vtimezones(self, minYear, maxYear=2018, filterzones=None):
        """
        Generate iCalendar data for all VTIMEZONEs or just those specified
        """

        cal = Calendar()
        for zone in self.zones.itervalues():
            if filterzones and zone.name not in filterzones:
                continue
            vtz = zone.vtimezone(cal, self.rules, minYear, maxYear)
            cal.addComponent(vtz)

        return cal.getText()
开发者ID:eventable,项目名称:PyCalendar,代码行数:13,代码来源:tzconvert.py


示例9: _getTimezoneFromServer

    def _getTimezoneFromServer(self, tzinfo):
        # List all from the server
        url = "%s?action=get&tzid=%s" % (self.uri, tzinfo.tzid)
        log.debug("Getting timezone from secondary server: %s" % (url,))
        response = (yield getURL(url))
        if response is None or response.code / 100 != 2:
            returnValue(None)

        ct = response.headers.getRawHeaders("content-type", ("bogus/type",))[0]
        ct = ct.split(";", 1)
        ct = ct[0]
        if ct not in ("text/calendar",):
            log.error("Invalid content-type '%s' for tzid : %s" % (ct, tzinfo.tzid))
            returnValue(None)

        ical = response.data
        try:
            calendar = Calendar.parseText(ical)
        except InvalidData:
            log.error("Invalid calendar data for tzid: %s" % (tzinfo.tzid,))
            returnValue(None)
        ical = calendar.getText()

        tzinfo.md5 = hashlib.md5(ical).hexdigest()

        try:
            tzpath = os.path.join(self.basepath, tzinfo.tzid) + ".ics"
            if not os.path.exists(os.path.dirname(tzpath)):
                os.makedirs(os.path.dirname(tzpath))
            f = open(tzpath, "w")
            f.write(ical)
            f.close()
        except IOError, e:
            log.error("Unable to write calendar file for %s: %s" % (tzinfo.tzid, str(e)))
开发者ID:redtailtech,项目名称:calendarserver,代码行数:34,代码来源:timezonestdservice.py


示例10: _doNonEquality

        def _doNonEquality(caldata):
            cal1 = Calendar()
            cal1.parse(StringIO.StringIO(caldata))

            cal2 = Calendar()
            cal2.parse(StringIO.StringIO(caldata))
            cal2.addProperty(Property("X-FOO", "BAR"))

            self.assertNotEqual(cal1, cal2)
开发者ID:eventable,项目名称:PyCalendar,代码行数:9,代码来源:test_calendar.py


示例11: testjCalExample1

    def testjCalExample1(self):

        jcaldata = """["vcalendar",
  [
    ["calscale", {}, "text", "GREGORIAN"],
    ["prodid", {}, "text", "-//Example Inc.//Example Calendar//EN"],
    ["version", {}, "text", "2.0"]
  ],
  [
    ["vevent",
      [
        ["dtstamp", {}, "date-time", "2008-02-05T19:12:24Z"],
        ["dtstart", {}, "date", "2008-10-06"],
        ["summary", {}, "text", "Planning meeting"],
        ["uid", {}, "text", "4088E990AD89CB3DBB484909"]
      ],
      []
    ]
  ]
]
"""

        icaldata = """BEGIN:VCALENDAR
CALSCALE:GREGORIAN
PRODID:-//Example Inc.//Example Calendar//EN
VERSION:2.0
BEGIN:VEVENT
DTSTAMP:20080205T191224Z
DTSTART;VALUE=DATE:20081006
SUMMARY:Planning meeting
UID:4088E990AD89CB3DBB484909
END:VEVENT
END:VCALENDAR
""".replace("\n", "\r\n")

        cal1 = Calendar.parseText(icaldata)
        test1 = cal1.getText()

        cal2 = Calendar.parseJSONData(jcaldata)
        test2 = cal2.getText()

        self.assertEqual(
            test1,
            test2,
            "\n".join(difflib.unified_diff(str(test1).splitlines(), test2.splitlines()))
        )
开发者ID:eventable,项目名称:PyCalendar,代码行数:46,代码来源:test_json.py


示例12: testDuplicateWithRecurrenceChange

    def testDuplicateWithRecurrenceChange(self):

        data = (
            """BEGIN:VCALENDAR
VERSION:2.0
CALSCALE:GREGORIAN
PRODID:-//mulberrymail.com//Mulberry v4.0//EN
BEGIN:VEVENT
UID:C3184A66-1ED0-11D9-A5E0-000A958A3252
DTSTART;VALUE=DATE:20020101
DTEND;VALUE=DATE:20020102
DTSTAMP:20020101T000000Z
RRULE:FREQ=YEARLY
SUMMARY:New Year's Day
END:VEVENT
END:VCALENDAR
""".replace("\n", "\r\n"),
            """BEGIN:VCALENDAR
VERSION:2.0
CALSCALE:GREGORIAN
PRODID:-//mulberrymail.com//Mulberry v4.0//EN
BEGIN:VEVENT
UID:C3184A66-1ED0-11D9-A5E0-000A958A3252
DTSTART;VALUE=DATE:20020101
DTEND;VALUE=DATE:20020102
DTSTAMP:20020101T000000Z
RRULE:FREQ=YEARLY;COUNT=400
SUMMARY:New Year's Day
END:VEVENT
END:VCALENDAR
""".replace("\n", "\r\n"),
        )

        cal1 = Calendar()
        cal1.parse(StringIO.StringIO(data[0]))
        cal2 = cal1.duplicate()
        vevent = cal2.getComponents()[0]
        rrules = vevent.getRecurrenceSet()
        for rrule in rrules.getRules():
            rrule.setUseCount(True)
            rrule.setCount(400)
            rrules.changed()

        self.assertEqual(data[0], str(cal1))
        self.assertEqual(data[1], str(cal2))
开发者ID:eventable,项目名称:PyCalendar,代码行数:45,代码来源:test_componentrecur.py


示例13: _doDuplicateRoundtrip

        def _doDuplicateRoundtrip(caldata):
            cal = Calendar()
            cal.parse(StringIO.StringIO(caldata))
            cal = cal.duplicate()

            s = StringIO.StringIO()
            cal.generate(s)
            self.assertEqual(caldata, s.getvalue())
开发者ID:eventable,项目名称:PyCalendar,代码行数:8,代码来源:test_calendar.py


示例14: _doEquality

        def _doEquality(caldata):
            cal1 = Calendar()
            cal1.parse(StringIO.StringIO(caldata))

            cal2 = Calendar()
            cal2.parse(StringIO.StringIO(caldata))

            self.assertEqual(cal1, cal2, "%s\n\n%s" % (cal1, cal2,))
开发者ID:eventable,项目名称:PyCalendar,代码行数:8,代码来源:test_calendar.py


示例15: testAddCN

    def testAddCN(self):

        data = (
            """BEGIN:VCALENDAR
VERSION:2.0
CALSCALE:GREGORIAN
PRODID:-//mulberrymail.com//Mulberry v4.0//EN
BEGIN:VEVENT
UID:C3184A66-1ED0-11D9-A5E0-000A958A3252
DTSTART;VALUE=DATE:20020101
DTEND;VALUE=DATE:20020102
DTSTAMP:20020101T000000Z
RRULE:FREQ=YEARLY;UNTIL=20031231;BYMONTH=1
ORGANIZER:[email protected]
SUMMARY:New Year's Day
END:VEVENT
END:VCALENDAR
""".replace("\n", "\r\n"),

            "まだ",

            """BEGIN:VCALENDAR
VERSION:2.0
CALSCALE:GREGORIAN
PRODID:-//mulberrymail.com//Mulberry v4.0//EN
BEGIN:VEVENT
UID:C3184A66-1ED0-11D9-A5E0-000A958A3252
DTSTART;VALUE=DATE:20020101
DTEND;VALUE=DATE:20020102
DTSTAMP:20020101T000000Z
RRULE:FREQ=YEARLY;UNTIL=20031231;BYMONTH=1
ORGANIZER;CN=まだ:[email protected]
SUMMARY:New Year's Day
END:VEVENT
END:VCALENDAR
""".replace("\n", "\r\n"),

        )

        cal1 = Calendar()
        cal1.parse(StringIO.StringIO(data[0]))

        vevent = cal1.getComponents("VEVENT")[0]
        organizer = vevent.getProperties("ORGANIZER")[0]
        organizer.addParameter(Parameter("CN", data[1]))

        cal2 = Calendar()
        cal2.parse(StringIO.StringIO(data[2]))

        self.assertEqual(str(cal1), str(cal2))
开发者ID:eventable,项目名称:PyCalendar,代码行数:50,代码来源:test_i18n.py


示例16: validate

def validate(fname):
    """
    Check whether the contents of the specified file is valid iCalendar or vCard data.
    """

    with open(fname) as f:
        data = f.read()

    ParserContext.allRaise()

    if data.find("BEGIN:VCALENDAR") != -1:
        try:
            cal = Calendar.parseText(data)
        except ErrorBase, e:
            print "Failed to parse iCalendar: %r" % (e,)
            sys.exit(1)
开发者ID:eventable,项目名称:PyCalendar,代码行数:16,代码来源:validator.py


示例17: _calProperty

    def _calProperty(self, propertyname, respdata):

        try:
            cal = Calendar.parseText(respdata)
        except Exception:
            return None

        # propname is a path consisting of component names and the last one a property name
        # e.g. VEVENT/ATTACH
        bits = propertyname.split("/")
        components = bits[:-1]
        prop = bits[-1]
        bits = prop.split("$")
        pname = bits[0]
        pvalue = bits[1] if len(bits) > 1 else None

        while components:
            for c in cal.getComponents():
                if c.getType() == components[0]:
                    cal = c
                    components = components[1:]
                    break
            else:
                break

        if components:
            return None

        props = cal.getProperties(pname)
        if pvalue:
            for prop in props:
                if prop.getValue().getValue() == pvalue:
                    return prop
            else:
                return None
        else:
            return props[0] if props else None
开发者ID:fpiotrow,项目名称:caldav-tester-packaging,代码行数:37,代码来源:caldavtest.py


示例18: anonymizeData

def anonymizeData(directoryMap, data):
    try:
        pyobj = Calendar.parseText(data)
    except Exception, e:
        print("Failed to parse (%s): %s" % (e, data))
        return None
开发者ID:eventable,项目名称:CalendarServer,代码行数:6,代码来源:anonymize.py


示例19:

import twistedcaldav.customxml
import twistedcaldav.timezonexml

twistedcaldav # Shhh.. pyflakes

#
# DefaultHTTPHandler
#

from txweb2.http_headers import DefaultHTTPHandler, last, singleHeader

DefaultHTTPHandler.updateParsers({
    "If-Schedule-Tag-Match": (last, str),
})
DefaultHTTPHandler.updateGenerators({
    "Schedule-Tag": (str, singleHeader),
})

# Do some PyCalendar init
from pycalendar.icalendar.calendar import Calendar
from pycalendar.icalendar.property import Property
from pycalendar.vcard.card import Card
from pycalendar.value import Value

Calendar.setPRODID("-//CALENDARSERVER.ORG//NONSGML Version 1//EN")
Card.setPRODID("-//CALENDARSERVER.ORG//NONSGML Version 1//EN")

# These are properties we use directly and we want the default value type set for TEXT
Property.registerDefaultValue("X-CALENDARSERVER-PRIVATE-COMMENT", Value.VALUETYPE_TEXT)
Property.registerDefaultValue("X-CALENDARSERVER-ATTENDEE-COMMENT", Value.VALUETYPE_TEXT)
开发者ID:svn2github,项目名称:calendarserver-raw,代码行数:30,代码来源:__init__.py


示例20: testCachePreserveOnAdjustment


#.........这里部分代码省略.........
RDATE:19420209T020000
TZNAME:EWT
TZOFFSETFROM:-0500
TZOFFSETTO:-0400
END:DAYLIGHT
BEGIN:DAYLIGHT
DTSTART:19450814T190000
RDATE:19450814T190000
TZNAME:EPT
TZOFFSETFROM:-0400
TZOFFSETTO:-0400
END:DAYLIGHT
BEGIN:DAYLIGHT
DTSTART:19460428T020000
RRULE:FREQ=YEARLY;UNTIL=19660424T070000Z;BYDAY=-1SU;BYMONTH=4
TZNAME:EDT
TZOFFSETFROM:-0500
TZOFFSETTO:-0400
END:DAYLIGHT
BEGIN:STANDARD
DTSTART:19460929T020000
RRULE:FREQ=YEARLY;UNTIL=19540926T060000Z;BYDAY=-1SU;BYMONTH=9
TZNAME:EST
TZOFFSETFROM:-0400
TZOFFSETTO:-0500
END:STANDARD
BEGIN:STANDARD
DTSTART:19551030T020000
RRULE:FREQ=YEARLY;UNTIL=19661030T060000Z;BYDAY=-1SU;BYMONTH=10
TZNAME:EST
TZOFFSETFROM:-0400
TZOFFSETTO:-0500
END:STANDARD
BEGIN:DAYLIGHT
DTSTART:19670430T020000
RRULE:FREQ=YEARLY;UNTIL=19730429T070000Z;BYDAY=-1SU;BYMONTH=4
TZNAME:EDT
TZOFFSETFROM:-0500
TZOFFSETTO:-0400
END:DAYLIGHT
BEGIN:STANDARD
DTSTART:19671029T020000
RRULE:FREQ=YEARLY;UNTIL=20061029T060000Z;BYDAY=-1SU;BYMONTH=10
TZNAME:EST
TZOFFSETFROM:-0400
TZOFFSETTO:-0500
END:STANDARD
BEGIN:DAYLIGHT
DTSTART:19760425T020000
RRULE:FREQ=YEARLY;UNTIL=19860427T070000Z;BYDAY=-1SU;BYMONTH=4
TZNAME:EDT
TZOFFSETFROM:-0500
TZOFFSETTO:-0400
END:DAYLIGHT
BEGIN:DAYLIGHT
DTSTART:19870405T020000
RRULE:FREQ=YEARLY;UNTIL=20060402T070000Z;BYDAY=1SU;BYMONTH=4
TZNAME:EDT
TZOFFSETFROM:-0500
TZOFFSETTO:-0400
END:DAYLIGHT
BEGIN:DAYLIGHT
DTSTART:20070311T020000
RRULE:FREQ=YEARLY;BYDAY=2SU;BYMONTH=3
TZNAME:EDT
TZOFFSETFROM:-0500
TZOFFSETTO:-0400
END:DAYLIGHT
BEGIN:STANDARD
DTSTART:20071104T020000
RRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=11
TZNAME:EST
TZOFFSETFROM:-0400
TZOFFSETTO:-0500
END:STANDARD
END:VTIMEZONE
END:VCALENDAR
""".replace("\n", "\r\n")

        Calendar.parseText(tzdata)

        dt = DateTime(2012, 6, 7, 12, 0, 0, Timezone(tzid="America/Pittsburgh"))
        dt.getPosixTime()

        # check existing cache is complete
        self.assertTrue(dt.mPosixTimeCached)
        self.assertNotEqual(dt.mPosixTime, 0)
        self.assertEqual(dt.mTZOffset, -14400)

        # duplicate preserves cache details
        dt2 = dt.duplicate()
        self.assertTrue(dt2.mPosixTimeCached)
        self.assertEqual(dt2.mPosixTime, dt.mPosixTime)
        self.assertEqual(dt2.mTZOffset, dt.mTZOffset)

        # adjust preserves cache details
        dt2.adjustToUTC()
        self.assertTrue(dt2.mPosixTimeCached)
        self.assertEqual(dt2.mPosixTime, dt.mPosixTime)
        self.assertEqual(dt2.mTZOffset, 0)
开发者ID:eventable,项目名称:PyCalendar,代码行数:101,代码来源:test_datetime.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python datastore_datatypes.Endpoint类代码示例发布时间:2022-05-25
下一篇:
Python datetime.PyCalendarDateTime类代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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