12.4 The mx.DateTime Module

DateTime is one of the modules in the mx package made available by eGenix GmbH. mx is open source, and at the time of this writing, mx.DateTime has liberal license conditions similar to those of Python itself. mx.DateTime's popularity stems from its functional richness and cross-platform portability. I present only an essential subset of mx.DateTime's rich functionality here; the module comes with detailed documentation about its advanced time and date handling features.

12.4.1 Date and Time Types

Module DateTime supplies several date and time types whose instances are immutable (and therefore suitable as dictionary keys). Type DateTime represents a time instant and includes an absolute date, which is the number of days since an epoch of January 1, year 1 CE, according to the Gregorian calendar (0001-01-01 is day 1), and an absolute time, which is a floating-point number of seconds since midnight. Type DateTimeDelta represents an interval of elapsed time, which is a floating-point number of seconds. Class RelativeDateTime lets you specify dates in relative terms, such as "next Monday" or "first day of next month." DateTime and DateTimeDelta are covered in detail later in this section, but RelativeDateTime is not.

Date and time types supply customized string conversion, invoked via the built-in str or automatically during implicit conversion (e.g., in a print statement). The resulting strings are in standard ISO 8601 formats, such as:

YYYY-MM-DD HH:MM:SS.ss

For finer-grained control of string formatting, use method strftime. Function DateTimeFrom constructs DateTime instances from strings. Submodules of module mx.DateTime supply other formatting and parsing functions, using different standards and conventions.

12.4.2 The DateTime Type

Module DateTime supplies factory functions to build instances of type DateTime, which in turn supply methods, attributes, and arithmetic operators.

12.4.2.1 Factory functions for DateTime

Module DateTime supplies many factory functions that produce DateTime instances. Several of these factory functions can also be invoked through synonyms. The most commonly used factory functions are the following.

DateTime, Date, Timestamp

DateTime(year,month=1,day=1,hour=0,minute=0,second=0.0)

Creates and returns a DateTime instance representing the given absolute time. Date and Timestamp are synonyms of DateTime. day can be less than 0 to denote days counted from the end of the month: -1 is the last day of the month, -2 the next to last day, and so on. For example:

print mx.DateTime.DateTime(2002,12,-1)     # prints: 2002-12-31 00:00:00.00

second is a floating-point value and can include an arbitrary fraction of a second.

DateTimeFrom, TimestampFrom

DateTimeFrom(*args,**kwds)

Creates and returns a DateTime instance built from the given arguments. TimestampFrom is a synonym of DateTimeFrom. DateTimeFrom can parse strings that represent a date and/or time. DateTimeFrom can also accept named arguments, taking the same names as those of the arguments of function DateTime.

DateTimeFromAbsDays

DateTimeFromAbsDays(days)

Creates and returns a DateTime instance representing an instant days days after the epoch. days is a floating-point number and can include an arbitrary fraction of a day.

DateTimeFromCOMDate

DateTimeFromCOMDate(comdate)

Creates and returns a DateTime instance representing the COM-format date comdate. comdate is a floating-point number and can include an arbitrary fraction of a day. The COM date epoch is midnight of January 1, 1900.

DateFromTicks

DateFromTicks(secs)

Creates and returns a DateTime instance representing midnight, local time, of the day of instant secs. secs is an instant as represented by the time module (i.e., seconds since time's epoch).

gmt, utc

gmt(  )

Creates and returns a DateTime instance representing the current GMT time. utc is a synonym of gmt.

gmtime, utctime

gmtime(secs=None)

Creates and returns a DateTime instance representing the GMT time of instant secs. secs is an instant as represented by the time module (i.e., seconds since time's epoch). When secs is None, gmtime uses the current instant as returned by function time.time. utctime is a synonym of gmtime.

localtime

localtime(secs=None)

Creates and returns a DateTime instance representing the local time of instant secs. secs is an instant as represented by the time module (i.e., seconds since time's epoch). When secs is None, localtime uses the current instant as returned by function time.time.

mktime

mktime(timetuple)

Creates and returns a DateTime instance representing the instant indicated by nine-item tuple timetuple, which is in the format used by module time.

now

now(  )

Creates and returns a DateTime instance representing the current local time.

TimestampFromTicks

TimestampFromTicks(secs)

Creates and returns a DateTime instance representing the local time of instant secs. secs is an instant as represented by the time module (i.e., seconds since time's epoch).

today

today(hour=0,minute=0,second=0.0)

Creates and returns a DateTime instance representing the local time for the given time (the default is midnight) of today's date.

12.4.2.2 Methods of DateTime instances

The most commonly used methods of a DateTime instance d are the following.

absvalues

d.absvalues(  )

Returns a pair (ad,at) where ad is an integer representing d's absolute date and at is a floating-point number representing d's absolute time.

COMDate

d.COMDate(  )

Returns d's instant in COM format (i.e., a floating-point number that is the number of days and fraction of a day since midnight of January 1, 1900).

gmticks

d.gmticks(  )

Returns a floating-point value representing d's instant as seconds (and fraction) since module time's epoch, assuming d is represented in GMT.

gmtime

d.gmtime(  )

Returns a DateTime instance d1 representing d's instant in GMT, assuming d is represented in local time.

gmtoffset

d.gmtoffset(  )

Returns a DateTimeDelta instance representing the time zone of d, assuming d is represented in local time. gmtoffset returns negative values in the Americas, positive ones in most of Europe, Asia, and Africa.

localtime

d.localtime(  )

Returns a DateTime instance d1 representing d's instant in local time, assuming d is represented in GMT.

strftime, Format

d.strftime(fmt="%c")

Returns a string representing d as specified by string fmt. The syntax of fmt is the same as in time.strftime, covered in Section 12.1 earlier in this chapter. Format is a synonym of strftime.

ticks

d.ticks(  )

Returns a floating-point number representing d's instant as seconds (and fraction) since module time's epoch, assuming d is represented in local time.

tuple

d.tuple(  )

Returns d's instant as a nine-item tuple, in the format used by module time.

12.4.2.3 Attributes of DateTime instances

The most commonly used attributes of a DateTime instance d are the following (all read-only):

absdate

d's absolute date, like d.absvalues( )[0]

absdays

A floating-point number representing days (and fraction of a day) since the epoch

abstime

d's absolute time, like d.absvalues( )[1]

date

A string in format 'YYYY-MM-DD', the standard ISO format for the date of d

day

An integer between 1 and 31, the day of the month of d

day_of_week

An integer between 0 and 6, the day of the week of d (Monday is 0)

day_of_year

An integer between 1 and 366, the day of the year of d (January 1 is 1)

dst

An integer between -1 and 1, indicating whether DST is in effect on date d, assuming d is represented in local time (-1 is unknown, 0 is no, 1 is yes)

hour

An integer between 0 and 23, the hour of the day of d

iso_week

A three-item tuple (year, week, day) with the ISO week notation for d (week is week-of-year; day is between 1, Monday, and 7, Sunday)

minute

An integer between 0 and 59, the minute of the hour of d

month

An integer between 1 and 12, the month of the year of d

second

A floating-point number between 0.0 and 60.0, the second of the minute of d (DateTime instances do not support leap seconds)

year

An integer, the year of d (1 is 1 CE, 0 is 1 BCE)

12.4.2.4 Arithmetic on DateTime instances

You can use binary operator - (minus) between two DateTime instances d1 and d2. In this case, d1-d2 is a DateTimeDelta instance representing the elapsed time between d1 and d2, which is greater than 0 if d1 is later than d2. You can use binary operators + and - between a DateTime instance d and a number n. d+n, d-n, and n+d are all DateTime instances differing from d by n (or -n) days (and fraction of a day, if n is a floating-point number), and n-d is arbitrarily defined to be equal to d-n.

12.4.3 The DateTimeDelta Type

Instances of type DateTimeDelta represent differences between time instants. Internally, a DateTimeDelta instance stores a floating-point number that represents a number of seconds (and fraction of a second).

12.4.3.1 Factory functions for DateTimeDelta

Module DateTime supplies many factory functions that produce DateTimeDelta instances. Some of these factory functions can be invoked through one or more synonyms. The most commonly used are the following.

DateTimeDelta

DateTimeDelta(days,hours=0.0,minutes=0.0,seconds=0.0)

Creates and returns a DateTimeDelta instance by the formula:

seconds+60.0*(minutes+60.0*(hours+24.0*days))
DateTimeDeltaFrom

DateTimeDeltaFrom(*args,**kwds)

Creates and returns a DateTimeDelta instance from the given arguments. See the DateTimeFrom factory function for type DateTime earlier in this chapter.

DateTimeDeltaFromSeconds

DateTimeDeltaFromSeconds(seconds)

Like DateTimeDelta(0,0,0,seconds).

TimeDelta, Time

TimeDelta(hours=0.0,minutes=0.0,seconds=0.0)

Like DateTimeDelta(0,hours,minutes,seconds). Function TimeDelta is guaranteed to accept named arguments. Time is a synonym for TimeDelta.

TimeDeltaFrom, TimeFrom

TimeDeltaFrom(*args,**kwds)

Like DateTimeDeltaFrom, except that the first positional numeric arguments, if any, indicate hours, not days as for DateTimeDeltaFrom. TimeFrom is a synonym for TimeDeltaFrom.

TimeFromTicks

TimeFromTicks(secs)

Creates and returns a DateTimeDelta instance for the amount of time between the instant secs (in the format used by the time module) and midnight of the same day as that of the instant secs.

12.4.3.2 Methods of DateTimeDelta instances

The most commonly used methods of a DateTimeDelta instance d are the following.

absvalues

d.absvalues(  )

Returns a pair (ad,at) where ad is an integer (d's number of days), at is a floating-point number (d's number of seconds modulo 86400), and both have the same sign.

strftime, Format

d.strftime(fmt="%c")

Returns a string representing d as specified by string fmt. The syntax of fmt is the same as in time.strftime, covered in Section 12.1 earlier in this chapter, but not all specifiers are meaningful. The result of d.strftime does not reflect the sign of the time interval that d represents; to display the sign as well, you must affix it to the string by separate string manipulation. For example:

if d.seconds >= 0.0: return d.strftime(fmt) else: return '-' + d.strftime(fmt)

Format is a synonym of strftime.

tuple

d.tuple(  )

Returns a tuple (day,hour,minute,second) where each item is a signed number in the respective range. second is a floating-point number, and the other items are integers.

12.4.3.3 Attributes of DateTimeDelta instances

A DateTimeDelta instance d supplies the following attributes (all read-only):

day , hour, minute, second

Like the four items of the tuple returned by d.tuple( )

days , hours, minutes, seconds

Each is a floating-point value expressing d's value in the given unit of measure, so that:

d.seconds == 60.0*d.minutes == 3600.0*d.hours == 86400.0*d.days
12.4.3.4 Arithmetic on DateTimeDelta instances

You can add or subtract two DateTimeDelta instances d1 and d2, to add or subtract the signed time intervals they represent. You can use binary operators + and - between a DateTimeDelta instance d and a number n: n is taken as a number of seconds (and fraction of a second, if n is a floating-point value). You can also multiply or divide d by n, to scale the time interval d represents. Each of these operations yields another DateTimeDelta instance. You can also add or subtract a DateTimeDelta instance dd to or from a DateTime instance d, yielding another DateTime instance d1 that differs from d by the signed time interval indicated by dd.

12.4.4 Other Attributes

Module mx.DateTime also supplies many constant attributes. The attributes used most often are:

oneWeek , oneDay, oneHour, oneMinute, oneSecond

Instances of DateTimeDelta representing the indicated durations

Monday , Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday

Integers representing the weekdays: Monday is 0, Tuesday is 1, and so on

Weekday

A dictionary that maps integer weekday numbers to their string names and vice versa: 0 maps to 'Monday', 'Monday' maps to 0, and so on

January , February, March, April, May, June, July, August, September, October, November, December

Integers representing the months: January is 1, February is 2, and so on

Month

A dictionary that maps integer month numbers to their string names and vice versa: 1 maps to 'January', 'January' maps to 1, and so on

Module mx.DateTime supplies one other useful function.

cmp

cmp(obj1,obj2,accuracy=0.0)

Compares two DateTime or DateTimeDelta instances obj1 and obj2, and returns -1, 0, or 1, like the built-in function cmp. It also returns 0 (meaning that obj1 and obj2 are "equal") if the two instants or durations differ by less than accuracy seconds.

12.4.5 Submodules

Module mx.DateTime also supplies several submodules for specialized purposes. Module mx.DateTime.ISO supplies functions to parse and generate date and time strings in ISO 8601 formats. Module mx.DateTime.ARPA supplies functions to parse and generate date and time strings in the ARPA format that is widely used on the Internet:

[Day, ]DD Mon YYYY HH:MM[:SS] [ZONE]

Module mx.DateTime.Feasts supplies functions to compute the date of Easter Sunday, and other moveable feast days that depend on it, for any given year. If your machine is connected to the Internet, you can use module mx.DateTime.NIST to access the accurate world standard time provided by NIST atomic clocks. Thanks to NIST's atomic clocks, the module is able to compute the current date and time very accurately. The module calibrates your computer's approximate clock with reference to NIST's clocks and compensates for any network delays incurred while accessing NIST.



Python in a Nutshell
Python in a Nutshell, Second Edition (In a Nutshell)
ISBN: 0596100469
EAN: 2147483647
Year: 2005
Pages: 203
Authors: Alex Martelli

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net