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


Python DateTime.getToday方法代码示例

本文整理汇总了Python中pycalendar.datetime.DateTime.getToday方法的典型用法代码示例。如果您正苦于以下问题:Python DateTime.getToday方法的具体用法?Python DateTime.getToday怎么用?Python DateTime.getToday使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pycalendar.datetime.DateTime的用法示例。


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

示例1: test_calendar_query_bogus_timezone_id

# 需要导入模块: from pycalendar.datetime import DateTime [as 别名]
# 或者: from pycalendar.datetime.DateTime import getToday [as 别名]
    def test_calendar_query_bogus_timezone_id(self):
        """
        Partial retrieval of events by time range.
        (CalDAV-access-09, section 7.6.1)
        """
        TimezoneCache.create()
        self.addCleanup(TimezoneCache.clear)

        calendar_properties = (
            davxml.GETETag(),
            caldavxml.CalendarData(),
        )

        query_timerange = caldavxml.TimeRange(
            start="%04d1001T000000Z" % (DateTime.getToday().getYear(),),
            end="%04d1101T000000Z" % (DateTime.getToday().getYear(),),
        )

        query = caldavxml.CalendarQuery(
            davxml.PropertyContainer(*calendar_properties),
            caldavxml.Filter(
                caldavxml.ComponentFilter(
                    caldavxml.ComponentFilter(
                        query_timerange,
                        name="VEVENT",
                    ),
                    name="VCALENDAR",
                ),
            ),
            caldavxml.TimeZoneID.fromString("bogus"),
        )

        result = yield self.calendar_query(query, got_xml=None, expected_code=responsecode.FORBIDDEN)
        self.assertTrue("valid-timezone" in result)
开发者ID:eventable,项目名称:CalendarServer,代码行数:36,代码来源:test_calendarquery.py

示例2: _doRefresh

# 需要导入模块: from pycalendar.datetime import DateTime [as 别名]
# 或者: from pycalendar.datetime.DateTime import getToday [as 别名]
def _doRefresh(tzpath, xmlfile, tzdb, tzvers):
    """
    Refresh data from IANA.
    """

    print("Downloading latest data from IANA")
    if tzvers:
        path = "https://www.iana.org/time-zones/repository/releases/tzdata%s.tar.gz" % (tzvers,)
    else:
        path = "https://www.iana.org/time-zones/repository/tzdata-latest.tar.gz"
    data = urllib.urlretrieve(path)
    print("Extract data at: %s" % (data[0]))
    rootdir = tempfile.mkdtemp()
    zonedir = os.path.join(rootdir, "tzdata")
    os.mkdir(zonedir)
    with tarfile.open(data[0], "r:gz") as t:
        t.extractall(zonedir)

    # Get the version from the Makefile
    try:
        makefile = open(os.path.join(zonedir, "Makefile")).read()
        lines = makefile.splitlines()
        for line in lines:
            if line.startswith("VERSION="):
                tzvers = line[8:].strip()
                break
    except IOError:
        pass

    if not tzvers:
        tzvers = DateTime.getToday().getText()
    print("Converting data (version: %s) at: %s" % (tzvers, zonedir,))
    startYear = 1800
    endYear = DateTime.getToday().getYear() + 10
    Calendar.sProdID = "-//calendarserver.org//Zonal//EN"
    zonefiles = "northamerica", "southamerica", "europe", "africa", "asia", "australasia", "antarctica", "etcetera", "backward"
    parser = tzconvert()
    for file in zonefiles:
        parser.parse(os.path.join(zonedir, file))

    parser.generateZoneinfoFiles(os.path.join(rootdir, "zoneinfo"), startYear, endYear, filterzones=())
    print("Copy new zoneinfo to destination: %s" % (tzpath,))
    z = FilePath(os.path.join(rootdir, "zoneinfo"))
    tz = FilePath(tzpath)
    z.copyTo(tz)
    print("Updating XML file at: %s" % (xmlfile,))
    tzdb.readDatabase()
    tzdb.updateDatabase()
    print("Current total: %d" % (len(tzdb.timezones),))
    print("Total Changed: %d" % (tzdb.changeCount,))
    if tzdb.changeCount:
        print("Changed:")
        for k in sorted(tzdb.changed):
            print("  %s" % (k,))

    versfile = os.path.join(os.path.dirname(xmlfile), "version.txt")
    print("Updating version file at: %s" % (versfile,))
    with open(versfile, "w") as f:
        f.write(TimezoneCache.IANA_VERSION_PREFIX + tzvers)
开发者ID:svn2github,项目名称:calendarserver-raw,代码行数:61,代码来源:managetimezones.py

示例3: setUpCalendarStore

# 需要导入模块: from pycalendar.datetime import DateTime [as 别名]
# 或者: from pycalendar.datetime.DateTime import getToday [as 别名]
def setUpCalendarStore(test):
    test.root = FilePath(test.mktemp())
    test.root.createDirectory()

    storeRootPath = test.storeRootPath = test.root.child("store")
    calendarPath = storeRootPath.child("calendars").child("__uids__")
    calendarPath.parent().makedirs()
    storePath.copyTo(calendarPath)

    # Set year values to current year
    nowYear = DateTime.getToday().getYear()
    for home in calendarPath.child("ho").child("me").children():
        if not home.basename().startswith("."):
            for calendar in home.children():
                if not calendar.basename().startswith("."):
                    for resource in calendar.children():
                        if resource.basename().endswith(".ics"):
                            resource.setContent(resource.getContent() % {"now": nowYear})

    testID = test.id()
    test.calendarStore = CalendarStore(
        storeRootPath,
        {"push": test.notifierFactory} if test.notifierFactory else {},
        buildDirectory(),
        quota=deriveQuota(test),
    )
    test.txn = test.calendarStore.newTransaction(testID + "(old)")
    assert test.calendarStore is not None, "No calendar store?"
开发者ID:svn2github,项目名称:calendarserver-raw,代码行数:30,代码来源:test_file.py

示例4: updateToCurrentYear

# 需要导入模块: from pycalendar.datetime import DateTime [as 别名]
# 或者: from pycalendar.datetime.DateTime import getToday [as 别名]
def updateToCurrentYear(data):
    """
    Update the supplied iCalendar data so that all dates are updated to the current year.
    """

    nowYear = DateTime.getToday().getYear()
    return data % {"now": nowYear}
开发者ID:nunb,项目名称:calendarserver,代码行数:9,代码来源:util.py

示例5: test_calendar_query_timezone

# 需要导入模块: from pycalendar.datetime import DateTime [as 别名]
# 或者: from pycalendar.datetime.DateTime import getToday [as 别名]
    def test_calendar_query_timezone(self):
        """
        Partial retrieval of events by time range.
        (CalDAV-access-09, section 7.6.1)
        """
        TimezoneCache.create()
        self.addCleanup(TimezoneCache.clear)

        tzid1 = "Etc/GMT+1"
        tz1 = Component(None, pycalendar=readVTZ(tzid1))

        calendar_properties = (
            davxml.GETETag(),
            caldavxml.CalendarData(),
        )

        query_timerange = caldavxml.TimeRange(
            start="%04d1001T000000Z" % (DateTime.getToday().getYear(),),
            end="%04d1101T000000Z" % (DateTime.getToday().getYear(),),
        )

        query = caldavxml.CalendarQuery(
            davxml.PropertyContainer(*calendar_properties),
            caldavxml.Filter(
                caldavxml.ComponentFilter(
                    caldavxml.ComponentFilter(
                        query_timerange,
                        name="VEVENT",
                    ),
                    name="VCALENDAR",
                ),
            ),
            caldavxml.TimeZone.fromCalendar(tz1),
        )

        def got_xml(doc):
            if not isinstance(doc.root_element, davxml.MultiStatus):
                self.fail("REPORT response XML root element is not multistatus: %r" % (doc.root_element,))

        return self.calendar_query(query, got_xml)
开发者ID:eventable,项目名称:CalendarServer,代码行数:42,代码来源:test_calendarquery.py

示例6: updateToCurrentYear

# 需要导入模块: from pycalendar.datetime import DateTime [as 别名]
# 或者: from pycalendar.datetime.DateTime import getToday [as 别名]
def updateToCurrentYear(data):
    """
    Update the supplied iCalendar data so that all dates are updated to the
    current year.
    """

    subs = {}
    nowYear = DateTime.getToday().getYear()
    subs["now"] = nowYear
    for i in range(1, 10):
        subs["now-{}".format(i)] = nowYear - 1
        subs["now+{}".format(i)] = nowYear + 1
    return data % subs
开发者ID:eventable,项目名称:CalendarServer,代码行数:15,代码来源:util.py

示例7: test_calendar_query_wrong_timezone_elements

# 需要导入模块: from pycalendar.datetime import DateTime [as 别名]
# 或者: from pycalendar.datetime.DateTime import getToday [as 别名]
    def test_calendar_query_wrong_timezone_elements(self):
        """
        Partial retrieval of events by time range.
        (CalDAV-access-09, section 7.6.1)
        """
        TimezoneCache.create()
        self.addCleanup(TimezoneCache.clear)

        tzid1 = "Etc/GMT+1"
        tz1 = Component(None, pycalendar=readVTZ(tzid1))

        calendar_properties = (
            davxml.GETETag(),
            caldavxml.CalendarData(),
        )

        query_timerange = caldavxml.TimeRange(
            start="%04d1001T000000Z" % (DateTime.getToday().getYear(),),
            end="%04d1101T000000Z" % (DateTime.getToday().getYear(),),
        )

        query = caldavxml.CalendarQuery(
            davxml.PropertyContainer(*calendar_properties),
            caldavxml.Filter(
                caldavxml.ComponentFilter(
                    caldavxml.ComponentFilter(
                        query_timerange,
                        name="VEVENT",
                    ),
                    name="VCALENDAR",
                ),
            ),
            caldavxml.TimeZone.fromCalendar(tz1),
        )
        query.children += (caldavxml.TimeZoneID.fromString(tzid1),)

        result = yield self.calendar_query(query, got_xml=None, expected_code=responsecode.BAD_REQUEST)
        self.assertTrue("Only one of" in result)
开发者ID:eventable,项目名称:CalendarServer,代码行数:40,代码来源:test_calendarquery.py

示例8: command_purgeOldEvents

# 需要导入模块: from pycalendar.datetime import DateTime [as 别名]
# 或者: from pycalendar.datetime.DateTime import getToday [as 别名]
    def command_purgeOldEvents(self, command):
        """
        Convert RetainDays from the command dictionary into a date, then purge
        events older than that date.

        @param command: the dictionary parsed from the plist read from stdin
        @type command: C{dict}
        """
        retainDays = command.get("RetainDays", DEFAULT_RETAIN_DAYS)
        cutoff = DateTime.getToday()
        cutoff.setDateOnly(False)
        cutoff.offsetDay(-retainDays)
        eventCount = (yield PurgeOldEventsService.purgeOldEvents(self.store, cutoff, DEFAULT_BATCH_SIZE))
        self.respond(command, {'EventsRemoved': eventCount, "RetainDays": retainDays})
开发者ID:nunb,项目名称:calendarserver,代码行数:16,代码来源:gateway.py

示例9: purgeAttachments

# 需要导入模块: from pycalendar.datetime import DateTime [as 别名]
# 或者: from pycalendar.datetime.DateTime import getToday [as 别名]
    def purgeAttachments(cls, store, uuid, days, limit, dryrun, verbose):

        service = cls(store)
        service.uuid = uuid
        if days > 0:
            cutoff = DateTime.getToday()
            cutoff.setDateOnly(False)
            cutoff.offsetDay(-days)
            service.cutoff = cutoff
        else:
            service.cutoff = None
        service.batchSize = limit
        service.dryrun = dryrun
        service.verbose = verbose
        result = (yield service.doWork())
        returnValue(result)
开发者ID:svn2github,项目名称:calendarserver-raw,代码行数:18,代码来源:purge.py

示例10: componentUpdate

# 需要导入模块: from pycalendar.datetime import DateTime [as 别名]
# 或者: from pycalendar.datetime.DateTime import getToday [as 别名]
def componentUpdate(data):
    """
    Update the supplied iCalendar data so that all dates are updated to the current year.
    """

    if len(relativeDateSubstitutions) == 0:
        now = DateTime.getToday()

        relativeDateSubstitutions["now"] = now

        for i in range(30):
            attrname = "now_back%s" % (i + 1,)
            dt = now.duplicate()
            dt.offsetDay(-(i + 1))
            relativeDateSubstitutions[attrname] = dt

        for i in range(30):
            attrname = "now_fwd%s" % (i + 1,)
            dt = now.duplicate()
            dt.offsetDay(i + 1)
            relativeDateSubstitutions[attrname] = dt

    return Component.fromString(data.format(**relativeDateSubstitutions))
开发者ID:nunb,项目名称:calendarserver,代码行数:25,代码来源:util.py

示例11: test_purgeOldEvents_old_cutoff

# 需要导入模块: from pycalendar.datetime import DateTime [as 别名]
# 或者: from pycalendar.datetime.DateTime import getToday [as 别名]
    def test_purgeOldEvents_old_cutoff(self):

        # Dry run
        cutoff = DateTime.getToday()
        cutoff.setDateOnly(False)
        cutoff.offsetDay(-400)

        total = (yield PurgeOldEventsService.purgeOldEvents(
            self._sqlCalendarStore,
            "ho",
            cutoff,
            2,
            dryrun=True,
            debug=True
        ))
        self.assertEquals(total, 12)

        # Actually remove
        total = (yield PurgeOldEventsService.purgeOldEvents(
            self._sqlCalendarStore,
            None,
            cutoff,
            2,
            debug=True
        ))
        self.assertEquals(total, 12)

        total = (yield PurgeOldEventsService.purgeOldEvents(
            self._sqlCalendarStore,
            "ho",
            cutoff,
            2,
            dryrun=True,
            debug=True
        ))
        self.assertEquals(total, 0)
开发者ID:eventable,项目名称:CalendarServer,代码行数:38,代码来源:test_purge_old_events.py

示例12: setUpCalendarStore

# 需要导入模块: from pycalendar.datetime import DateTime [as 别名]
# 或者: from pycalendar.datetime.DateTime import getToday [as 别名]
def setUpCalendarStore(test):
    test.root = FilePath(test.mktemp())
    test.root.createDirectory()

    storeRootPath = test.storeRootPath = test.root.child("store")
    calendarPath = storeRootPath.child("calendars").child("__uids__")
    calendarPath.parent().makedirs()
    storePath.copyTo(calendarPath)

    # Set year values to current year
    subs = {}
    nowYear = DateTime.getToday().getYear()
    subs["now"] = nowYear
    for i in range(1, 10):
        subs["now-{}".format(i)] = nowYear - 1
        subs["now+{}".format(i)] = nowYear + 1
    for home in calendarPath.child("ho").child("me").children():
        if not home.basename().startswith("."):
            for calendar in home.children():
                if not calendar.basename().startswith("."):
                    for resource in calendar.children():
                        if resource.basename().endswith(".ics"):
                            resource.setContent(resource.getContent() % subs)

    testID = test.id()
    test.counter = 0
    test.notifierFactory = StubNotifierFactory()
    test.calendarStore = CalendarStore(
        storeRootPath,
        {"push": test.notifierFactory} if test.notifierFactory else {},
        None,  # must create directory later
        quota=deriveQuota(test),
    )
    test.directory = buildTestDirectory(test.calendarStore, test.mktemp())
    test.txn = test.calendarStore.newTransaction(testID + "(old)")
    assert test.calendarStore is not None, "No calendar store?"
开发者ID:eventable,项目名称:CalendarServer,代码行数:38,代码来源:test_file.py

示例13: _internalGenerateFreeBusyInfo

# 需要导入模块: from pycalendar.datetime import DateTime [as 别名]
# 或者: from pycalendar.datetime.DateTime import getToday [as 别名]
def _internalGenerateFreeBusyInfo(
    calresource,
    fbinfo,
    timerange,
    matchtotal,
    excludeuid=None,
    organizer=None,
    organizerPrincipal=None,
    same_calendar_user=False,
    servertoserver=False,
    event_details=None,
    logItems=None,
    accountingItems=None,
):
    """
    Run a free busy report on the specified calendar collection
    accumulating the free busy info for later processing.
    @param calresource: the L{Calendar} for a calendar collection.
    @param fbinfo:      the array of busy periods to update.
    @param timerange:   the L{TimeRange} for the query.
    @param matchtotal:  the running total for the number of matches.
    @param excludeuid:  a C{str} containing a UID value to exclude any
        components with that UID from contributing to free-busy.
    @param organizer:   a C{str} containing the value of the ORGANIZER property
        in the VFREEBUSY request.  This is used in conjunction with the UID
        value to process exclusions.
    @param same_calendar_user: a C{bool} indicating whether the calendar user
        requesting the free-busy information is the same as the calendar user
        being targeted.
    @param servertoserver: a C{bool} indicating whether we are doing a local or
        remote lookup request.
    @param event_details: a C{list} into which to store extended VEVENT details if not C{None}
    @param logItems: a C{dict} to store logging info to
    @param accountingItems: a C{dict} to store accounting info to
    """

    # First check the privilege on this collection
    # TODO: for server-to-server we bypass this right now as we have no way to authorize external users.
    # TODO: actually we by pass altogether by assuming anyone can check anyone else's freebusy

    # May need organizer principal
    organizer_record = (yield calresource.directoryService().recordWithCalendarUserAddress(organizer)) if organizer else None
    organizer_uid = organizer_record.uid if organizer_record else ""

    # Free busy is per-user
    attendee_uid = calresource.viewerHome().uid()
    attendee_record = yield calresource.directoryService().recordWithUID(attendee_uid.decode("utf-8"))

    # Get the timezone property from the collection.
    tz = calresource.getTimezone()

    # Look for possible extended free busy information
    rich_options = {
        "organizer": False,
        "delegate": False,
        "resource": False,
    }
    do_event_details = False
    if event_details is not None and organizer_record is not None and attendee_record is not None:

        # Get the principal of the authorized user which may be different from the organizer if a delegate of
        # the organizer is making the request
        authz_uid = organizer_uid
        authz_record = organizer_record
        if calresource._txn._authz_uid is not None and calresource._txn._authz_uid != organizer_uid:
            authz_uid = calresource._txn._authz_uid
            authz_record = yield calresource.directoryService().recordWithUID(authz_uid.decode("utf-8"))

        # Check if attendee is also the organizer or the delegate doing the request
        if attendee_uid in (organizer_uid, authz_uid):
            do_event_details = True
            rich_options["organizer"] = True

        # Check if authorized user is a delegate of attendee
        proxy = (yield authz_record.isProxyFor(attendee_record))
        if config.Scheduling.Options.DelegeteRichFreeBusy and proxy:
            do_event_details = True
            rich_options["delegate"] = True

        # Check if attendee is room or resource
        if config.Scheduling.Options.RoomResourceRichFreeBusy and attendee_record.getCUType() in ("RESOURCE", "ROOM",):
            do_event_details = True
            rich_options["resource"] = True

    # Try cache
    resources = (yield FBCacheEntry.getCacheEntry(calresource, attendee_uid, timerange)) if config.EnableFreeBusyCache else None

    if resources is None:

        if accountingItems is not None:
            accountingItems["fb-uncached"] = accountingItems.get("fb-uncached", 0) + 1

        caching = False
        if config.EnableFreeBusyCache:
            # Log extended item
            if logItems is not None:
                logItems["fb-uncached"] = logItems.get("fb-uncached", 0) + 1

            # We want to cache a large range of time based on the current date
            cache_start = normalizeToUTC(DateTime.getToday() + Duration(days=0 - config.FreeBusyCacheDaysBack))
#.........这里部分代码省略.........
开发者ID:nunb,项目名称:calendarserver,代码行数:103,代码来源:freebusy.py

示例14: in

# 需要导入模块: from pycalendar.datetime import DateTime [as 别名]
# 或者: from pycalendar.datetime.DateTime import getToday [as 别名]
            elif opt in ("-n", "--dry-run"):
                dryrun = True

            elif opt in ("-f", "--config"):
                configFileName = arg

            else:
                raise NotImplementedError(opt)

        if args:
            cls.usage("Too many arguments: %s" % (args,))

        if dryrun:
            verbose = True

        cutoff = DateTime.getToday()
        cutoff.setDateOnly(False)
        cutoff.offsetDay(-days)
        cls.cutoff = cutoff
        cls.batchSize = batchSize
        cls.dryrun = dryrun
        cls.verbose = verbose

        utilityMain(
            configFileName,
            cls,
            verbose=debug,
        )


    @classmethod
开发者ID:svn2github,项目名称:calendarserver-raw,代码行数:33,代码来源:purge.py

示例15: test_calendar_query_time_range

# 需要导入模块: from pycalendar.datetime import DateTime [as 别名]
# 或者: from pycalendar.datetime.DateTime import getToday [as 别名]
    def test_calendar_query_time_range(self):
        """
        Partial retrieval of events by time range.
        (CalDAV-access-09, section 7.6.1)
        """
        calendar_properties = (
            davxml.GETETag(),
            caldavxml.CalendarData(
                caldavxml.CalendarComponent(
                    caldavxml.AllProperties(),
                    caldavxml.CalendarComponent(
                        caldavxml.Property(name="X-ABC-GUID"),
                        caldavxml.Property(name="UID"),
                        caldavxml.Property(name="DTSTART"),
                        caldavxml.Property(name="DTEND"),
                        caldavxml.Property(name="DURATION"),
                        caldavxml.Property(name="EXDATE"),
                        caldavxml.Property(name="EXRULE"),
                        caldavxml.Property(name="RDATE"),
                        caldavxml.Property(name="RRULE"),
                        caldavxml.Property(name="LOCATION"),
                        caldavxml.Property(name="SUMMARY"),
                        name="VEVENT",
                    ),
                    caldavxml.CalendarComponent(
                        caldavxml.AllProperties(),
                        caldavxml.AllComponents(),
                        name="VTIMEZONE",
                    ),
                    name="VCALENDAR",
                ),
            ),
        )

        query_timerange = caldavxml.TimeRange(
            start="%04d1001T000000Z" % (DateTime.getToday().getYear(),),
            end="%04d1101T000000Z" % (DateTime.getToday().getYear(),),
        )

        query = caldavxml.CalendarQuery(
            davxml.PropertyContainer(*calendar_properties),
            caldavxml.Filter(
                caldavxml.ComponentFilter(
                    caldavxml.ComponentFilter(
                        query_timerange,
                        name="VEVENT",
                    ),
                    name="VCALENDAR",
                ),
            ),
        )

        def got_xml(doc):
            if not isinstance(doc.root_element, davxml.MultiStatus):
                self.fail("REPORT response XML root element is not multistatus: %r" % (doc.root_element,))

            for response in doc.root_element.childrenOfType(davxml.PropertyStatusResponse):
                properties_to_find = [p.qname() for p in calendar_properties]

                for propstat in response.childrenOfType(davxml.PropertyStatus):
                    status = propstat.childOfType(davxml.Status)
                    properties = propstat.childOfType(davxml.PropertyContainer).children

                    if status.code != responsecode.OK:
                        self.fail("REPORT failed (status %s) to locate properties: %r"
                                  % (status.code, properties))

                    for property in properties:
                        qname = property.qname()
                        if qname in properties_to_find:
                            properties_to_find.remove(qname)
                        else:
                            self.fail("REPORT found property we didn't ask for: %r" % (property,))

                        if isinstance(property, caldavxml.CalendarData):
                            cal = property.calendar()
                            instances = cal.expandTimeRanges(query_timerange.end)
                            vevents = [x for x in cal.subcomponents() if x.name() == "VEVENT"]
                            if not TimeRange(query_timerange).matchinstance(vevents[0], instances):
                                self.fail("REPORT property %r returned calendar %s outside of request time range %r"
                                          % (property, property.calendar, query_timerange))

        return self.calendar_query(query, got_xml)
开发者ID:nunb,项目名称:calendarserver,代码行数:85,代码来源:test_calendarquery.py


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