Logo Search packages:      
Sourcecode: zope version File versions

def DateTime::DateTime::DateTime::__init__ (   self,
  args 
)

Return a new date-time object

A DateTime object always maintains its value as an absolute
UTC time, and is represented in the context of some timezone
based on the arguments used to create the object. A DateTime
object's methods return values based on the timezone context.

Note that in all cases the local machine timezone is used for
representation if no timezone is specified.

DateTimes may be created with from zero to seven arguments.


  - If the function is called with no arguments, then the
    current date/time is returned, represented in the
    timezone of the local machine.

  - If the function is invoked with a single string argument
    which is a recognized timezone name, an object representing
    the current time is returned, represented in the specified
    timezone.

  - If the function is invoked with a single string argument
    representing a valid date/time, an object representing
    that date/time will be returned.

    As a general rule, any date-time representation that is
    recognized and unambigous to a resident of North America is
    acceptable.(The reason for this qualification is that
    in North America, a date like: 2/1/1994 is interpreted
    as February 1, 1994, while in some parts of the world,
    it is interpreted as January 2, 1994.) A date/time
    string consists of two components, a date component and
    an optional time component, separated by one or more
    spaces. If the time component is omited, 12:00am is
    assumed. Any recognized timezone name specified as the
    final element of the date/time string will be used for
    computing the date/time value. (If you create a DateTime
    with the string 'Mar 9, 1997 1:45pm US/Pacific', the
    value will essentially be the same as if you had captured
    time.time() at the specified date and time on a machine in
    that timezone)
    <PRE>

    e=DateTime('US/Eastern')
    # returns current date/time, represented in US/Eastern.

    x=DateTime('1997/3/9 1:45pm')
    # returns specified time, represented in local machine zone.

    y=DateTime('Mar 9, 1997 13:45:00')
    # y is equal to x


    </PRE>

    New in Zope 2.4:
    The DateTime constructor automatically detects and handles
    ISO8601 compliant dates (YYYY-MM-DDThh:ss:mmTZD).
    See http://www.w3.org/TR/NOTE-datetime for full specs.

    The date component consists of year, month, and day
    values. The year value must be a one-, two-, or
    four-digit integer. If a one- or two-digit year is
    used, the year is assumed to be in the twentieth
    century. The month may an integer, from 1 to 12, a
    month name, or a month abreviation, where a period may
    optionally follow the abreviation. The day must be an
    integer from 1 to the number of days in the month. The
    year, month, and day values may be separated by
    periods, hyphens, forward, shashes, or spaces. Extra
    spaces are permitted around the delimiters. Year,
    month, and day values may be given in any order as long
    as it is possible to distinguish the components. If all
    three components are numbers that are less than 13,
    then a a month-day-year ordering is assumed.

    The time component consists of hour, minute, and second
    values separated by colons.  The hour value must be an
    integer between 0 and 23 inclusively. The minute value
    must be an integer between 0 and 59 inclusively. The
    second value may be an integer value between 0 and
    59.999 inclusively. The second value or both the minute
    and second values may be ommitted. The time may be
    followed by am or pm in upper or lower case, in which
    case a 12-hour clock is assumed.

  - If the DateTime function is invoked with a single
    Numeric argument, the number is assumed to be
    a floating point value such as that returned by
    time.time().

    A DateTime object is returned that represents
    the gmt value of the time.time() float represented in
    the local machine's timezone.

  - If the function is invoked with two numeric arguments,
    then the first is taken to be an integer year and the
    second argument is taken to be an offset in days from
    the beginning of the year, in the context of the local
    machine timezone.
    The date-time value returned is the given offset number of
    days from the beginning of the given year, represented in
    the timezone of the local machine. The offset may be positive
    or negative.
    Two-digit years are assumed to be in the twentieth
    century.

  - If the function is invoked with two arguments, the first
    a float representing a number of seconds past the epoch
    in gmt (such as those returned by time.time()) and the
    second a string naming a recognized timezone, a DateTime
    with a value of that gmt time will be returned, represented
    in the given timezone.
    <PRE>
    import time
    t=time.time()

    now_east=DateTime(t,'US/Eastern')
    # Time t represented as US/Eastern

    now_west=DateTime(t,'US/Pacific')
    # Time t represented as US/Pacific

    # now_east == now_west
    # only their representations are different

    </PRE>

  - If the function is invoked with three or more numeric
    arguments, then the first is taken to be an integer
    year, the second is taken to be an integer month, and
    the third is taken to be an integer day. If the
    combination of values is not valid, then a
    DateError is raised. Two-digit years are assumed
    to be in the twentieth century. The fourth, fifth, and
    sixth arguments specify a time in hours, minutes, and
    seconds; hours and minutes should be positive integers
    and seconds is a positive floating point value, all of
    these default to zero if not given. An optional string may
    be given as the final argument to indicate timezone (the
    effect of this is as if you had taken the value of time.time()
    at that time on a machine in the specified timezone).

In any case that a floating point number of seconds is given
or derived, it's rounded to the nearest millisecond.

If a string argument passed to the DateTime constructor cannot be
parsed, it will raise DateTime.SyntaxError. Invalid date components
will raise a DateError, while invalid time or timezone components
will raise a DateTimeError.

The module function Timezones() will return a list of the
timezones recognized by the DateTime module. Recognition of
timezone names is case-insensitive.

Definition at line 458 of file DateTime.py.

00458                             :
        """Return a new date-time object

        A DateTime object always maintains its value as an absolute
        UTC time, and is represented in the context of some timezone
        based on the arguments used to create the object. A DateTime
        object's methods return values based on the timezone context.

        Note that in all cases the local machine timezone is used for
        representation if no timezone is specified.

        DateTimes may be created with from zero to seven arguments.


          - If the function is called with no arguments, then the
            current date/time is returned, represented in the
            timezone of the local machine.

          - If the function is invoked with a single string argument
            which is a recognized timezone name, an object representing
            the current time is returned, represented in the specified
            timezone.

          - If the function is invoked with a single string argument
            representing a valid date/time, an object representing
            that date/time will be returned.

            As a general rule, any date-time representation that is
            recognized and unambigous to a resident of North America is
            acceptable.(The reason for this qualification is that
            in North America, a date like: 2/1/1994 is interpreted
            as February 1, 1994, while in some parts of the world,
            it is interpreted as January 2, 1994.) A date/time
            string consists of two components, a date component and
            an optional time component, separated by one or more
            spaces. If the time component is omited, 12:00am is
            assumed. Any recognized timezone name specified as the
            final element of the date/time string will be used for
            computing the date/time value. (If you create a DateTime
            with the string 'Mar 9, 1997 1:45pm US/Pacific', the
            value will essentially be the same as if you had captured
            time.time() at the specified date and time on a machine in
            that timezone)
            <PRE>

            e=DateTime('US/Eastern')
            # returns current date/time, represented in US/Eastern.

            x=DateTime('1997/3/9 1:45pm')
            # returns specified time, represented in local machine zone.

            y=DateTime('Mar 9, 1997 13:45:00')
            # y is equal to x


            </PRE>

            New in Zope 2.4:
            The DateTime constructor automatically detects and handles
            ISO8601 compliant dates (YYYY-MM-DDThh:ss:mmTZD).
            See http://www.w3.org/TR/NOTE-datetime for full specs.

            The date component consists of year, month, and day
            values. The year value must be a one-, two-, or
            four-digit integer. If a one- or two-digit year is
            used, the year is assumed to be in the twentieth
            century. The month may an integer, from 1 to 12, a
            month name, or a month abreviation, where a period may
            optionally follow the abreviation. The day must be an
            integer from 1 to the number of days in the month. The
            year, month, and day values may be separated by
            periods, hyphens, forward, shashes, or spaces. Extra
            spaces are permitted around the delimiters. Year,
            month, and day values may be given in any order as long
            as it is possible to distinguish the components. If all
            three components are numbers that are less than 13,
            then a a month-day-year ordering is assumed.

            The time component consists of hour, minute, and second
            values separated by colons.  The hour value must be an
            integer between 0 and 23 inclusively. The minute value
            must be an integer between 0 and 59 inclusively. The
            second value may be an integer value between 0 and
            59.999 inclusively. The second value or both the minute
            and second values may be ommitted. The time may be
            followed by am or pm in upper or lower case, in which
            case a 12-hour clock is assumed.

          - If the DateTime function is invoked with a single
            Numeric argument, the number is assumed to be
            a floating point value such as that returned by
            time.time().

            A DateTime object is returned that represents
            the gmt value of the time.time() float represented in
            the local machine's timezone.

          - If the function is invoked with two numeric arguments,
            then the first is taken to be an integer year and the
            second argument is taken to be an offset in days from
            the beginning of the year, in the context of the local
            machine timezone.
            The date-time value returned is the given offset number of
            days from the beginning of the given year, represented in
            the timezone of the local machine. The offset may be positive
            or negative.
            Two-digit years are assumed to be in the twentieth
            century.

          - If the function is invoked with two arguments, the first
            a float representing a number of seconds past the epoch
            in gmt (such as those returned by time.time()) and the
            second a string naming a recognized timezone, a DateTime
            with a value of that gmt time will be returned, represented
            in the given timezone.
            <PRE>
            import time
            t=time.time()

            now_east=DateTime(t,'US/Eastern')
            # Time t represented as US/Eastern

            now_west=DateTime(t,'US/Pacific')
            # Time t represented as US/Pacific

            # now_east == now_west
            # only their representations are different

            </PRE>

          - If the function is invoked with three or more numeric
            arguments, then the first is taken to be an integer
            year, the second is taken to be an integer month, and
            the third is taken to be an integer day. If the
            combination of values is not valid, then a
            DateError is raised. Two-digit years are assumed
            to be in the twentieth century. The fourth, fifth, and
            sixth arguments specify a time in hours, minutes, and
            seconds; hours and minutes should be positive integers
            and seconds is a positive floating point value, all of
            these default to zero if not given. An optional string may
            be given as the final argument to indicate timezone (the
            effect of this is as if you had taken the value of time.time()
            at that time on a machine in the specified timezone).

        In any case that a floating point number of seconds is given
        or derived, it's rounded to the nearest millisecond.

        If a string argument passed to the DateTime constructor cannot be
        parsed, it will raise DateTime.SyntaxError. Invalid date components
        will raise a DateError, while invalid time or timezone components
        will raise a DateTimeError.

        The module function Timezones() will return a list of the
        timezones recognized by the DateTime module. Recognition of
        timezone names is case-insensitive.""" #'

        d=t=s=None
        ac=len(args)
        millisecs = None

        if ac and args[0]==None: return
        elif ac==10:
            # Internal format called only by DateTime
            yr,mo,dy,hr,mn,sc,tz,t,d,s=args
        elif ac == 11:
            # Internal format that includes milliseconds.
            yr,mo,dy,hr,mn,sc,tz,t,d,s,millisecs=args

        elif not args:
            # Current time, to be displayed in local timezone
            t = time()
            lt = safelocaltime(t)
            tz = self.localZone(lt)
            ms = (t - math.floor(t))
            s,d = _calcSD(t)
            yr,mo,dy,hr,mn,sc=lt[:6]
            sc=sc+ms

        elif ac==1:
            arg=args[0]

            if arg=='':
                raise self.SyntaxError, arg

            if type(arg) in [StringType,UnicodeType] and arg.lower() in self._tzinfo._zidx:
                # Current time, to be displayed in specified timezone
                t,tz=time(),self._tzinfo._zmap[arg.lower()]
                ms=(t-math.floor(t))
                # Use integer arithmetic as much as possible.
                s,d = _calcSD(t)
                x = _calcDependentSecond(tz, t)
                yr,mo,dy,hr,mn,sc = _calcYMDHMS(x, ms)

            elif type(arg) in [StringType,UnicodeType]:
                # Date/time string

                if arg.find(' ')==-1 and arg[4]=='-':
                    yr,mo,dy,hr,mn,sc,tz=self._parse_iso8601(arg)
                else:
                    yr,mo,dy,hr,mn,sc,tz=self._parse(arg)


                if not self._validDate(yr,mo,dy):
                    raise self.DateTimeError, 'Invalid date: %s' % arg
                if not self._validTime(hr,mn,int(sc)):
                    raise self.DateTimeError, 'Invalid time: %s' % arg
                ms = sc - math.floor(sc)
                x = _calcDependentSecond2(yr,mo,dy,hr,mn,sc)

                if tz:
                    try: tz=self._tzinfo._zmap[tz.lower()]
                    except KeyError:
                        if numericTimeZoneMatch(tz) is None:
                            raise self.DateTimeError, \
                                  'Unknown time zone in date: %s' % arg
                else:
                    tz = self._calcTimezoneName(x, ms)
                s,d,t,millisecs = _calcIndependentSecondEtc(tz, x, ms)

            else:
                # Seconds from epoch, gmt
                t = arg
                lt = safelocaltime(t)
                tz = self.localZone(lt)
                ms=(t-math.floor(t))
                s,d = _calcSD(t)
                yr,mo,dy,hr,mn,sc=lt[:6]
                sc=sc+ms

        elif ac==2:
            if type(args[1])==StringType:
                # Seconds from epoch (gmt) and timezone
                t,tz=args
                ms = (t - math.floor(t))
                tz=self._tzinfo._zmap[tz.lower()]
                # Use integer arithmetic as much as possible.
                s,d = _calcSD(t)
                x = _calcDependentSecond(tz, t)
                yr,mo,dy,hr,mn,sc = _calcYMDHMS(x, ms)
            else:
                # Year, julian expressed in local zone
                t = time()
                lt = safelocaltime(t)
                tz = self.localZone(lt)
                yr,jul=args
                yr = _correctYear(yr)
                d=(_julianday(yr,1,0)-jd1901)+jul
                x_float = d * 86400.0
                x_floor = math.floor(x_float)
                ms = x_float - x_floor
                x = long(x_floor)
                yr,mo,dy,hr,mn,sc = _calcYMDHMS(x, ms)
                s,d,t,millisecs = _calcIndependentSecondEtc(tz, x, ms)
        else:
            # Explicit format
            yr,mo,dy=args[:3]
            hr,mn,sc,tz=0,0,0,0
            yr = _correctYear(yr)
            if not self._validDate(yr,mo,dy):
                raise self.DateTimeError, 'Invalid date: %s' % (args,)
            args=args[3:]
            if args:
                hr,args=args[0],args[1:]
                if args:
                    mn,args=args[0],args[1:]
                    if args:
                        sc,args=args[0],args[1:]
                        if args:
                            tz,args=args[0],args[1:]
                            if args:
                                raise self.DateTimeError,'Too many arguments'
            if not self._validTime(hr,mn,sc):
                raise self.DateTimeError, 'Invalid time: %s' % `args`
            leap = (yr % 4 == 0) and (yr % 100 != 0 or yr % 400 == 0)

            x = _calcDependentSecond2(yr,mo,dy,hr,mn,sc)
            ms = sc - math.floor(sc)
            if tz:
                try: tz=self._tzinfo._zmap[tz.lower()]
                except KeyError:
                    if numericTimeZoneMatch(tz) is None:
                        raise self.DateTimeError, \
                              'Unknown time zone: %s' % tz
            else:
                # Get local time zone name
                tz = self._calcTimezoneName(x, ms)
            s,d,t,millisecs = _calcIndependentSecondEtc(tz, x, ms)

        if hr>12:
            self._pmhour=hr-12
            self._pm='pm'
        else:
            self._pmhour=hr or 12
            self._pm= (hr==12) and 'pm' or 'am'
        self._dayoffset=dx=int((_julianday(yr,mo,dy)+2L)%7)
        self._fmon,self._amon,self._pmon= \
            self._months[mo],self._months_a[mo],self._months_p[mo]
        self._fday,self._aday,self._pday= \
            self._days[dx],self._days_a[dx],self._days_p[dx]
        # Round to nearest millisecond in platform-independent way.  You
        # cannot rely on C sprintf (Python '%') formatting to round
        # consistently; doing it ourselves ensures that all but truly
        # horrid C sprintf implementations will yield the same result
        # x-platform, provided the format asks for exactly 3 digits after
        # the decimal point.
        sc = round(sc, 3)
        if sc >= 60.0:  # can happen if, e.g., orig sc was 59.9999
            sc = 59.999
        self._nearsec=math.floor(sc)
        self._year,self._month,self._day     =yr,mo,dy
        self._hour,self._minute,self._second =hr,mn,sc
        self.time,self._d,self._t,self._tz   =s,d,t,tz
        if millisecs is None:
            millisecs = long(math.floor(t * 1000.0))
        self._millis = millisecs
        # self._millis is the time since the epoch
        # in long integer milliseconds.

    DateTimeError='DateTimeError'
    SyntaxError  ='Invalid Date-Time String'


Generated by  Doxygen 1.6.0   Back to index