Section 12.7. The mx.DateTime Module


12.7. The mx.DateTime Module

DateTime is one of the modules in the mx package made available by eGenix GmbH. mx is mostly 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.7.1. Date and Time Types

Package DateTime supplies several date and time types whose instances are immutable (thus, suitable as dictionary keys). Type DateTime represents a time instant and includes an absolute date, 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, a floating-point number of seconds since midnight. Type DateTimeDelta represents an interval of 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 (respectively in "The DateTime Type" on page 319 and "The DateTimeDelta Type" on page 324), 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 ISO8601 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. Various modules of package mx.DateTime also supply other formatting and parsing functions.

12.7.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.7.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 is 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 also accepts named arguments, with the same names as those of the arguments of function DateTime.

DateTime-FromAbsDays

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.

DateTime-FromCOMDate

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.

Timestamp-FromTicks

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 (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.7.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 (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, and 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 "strftime". Format is a synonym of strftime.

ticks

d.ticks( )

Returns a floating-point number representing d's instant as seconds (and a 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.7.2.3. Attributes of DateTime instances

The most commonly used attributes of a DateTime instance d are the following (all are 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, and 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 seconds-within-minute of d (DateTime instances do not support leap seconds)


year

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

12.7.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 that differ 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.7.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 a fraction of a second).

12.7.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)) 

DateTimeDelta-From

DateTimeDeltaFrom(*args,**kwds)

Creates and returns a DateTimeDelta instance from the given arguments. See also "DateTimeFrom, TimestampFrom" on page 320.

DateTimeDelta-FromSeconds

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 positional arguments, if any, indicate hours, not days as for DateTimeDeltaFrom. TimeFrom is the same as TimeDeltaFrom.

TimeFromTicks

TimeFromTicks(secs)

Creates and returns a DateTimeDelta instance for the amount of time between instant secs (in seconds since the epoch) and midnight of the same day as that of instant secs.


12.7.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 strftime on page 304, 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, affix it to the string by 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); each item is a signed number in the respective range. second is a floating-point number, and the other items are integers.


12.7.3.3. Attributes of DateTimeDelta instances

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


day hour minute second

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


days hours minutes seconds

Each a floating-point value giving 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.7.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 multiply or divide d by n to scale the time interval d represents. Each operation returns a DateTimeDelta instance. You can also add or subtract a DateTimeDelta instance dd to or from a DateTime instance d to get another DateTime instance d1 that differs from d by the signed time interval indicated by dd.

12.7.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 that represent the indicated durations


Monday Tuesday Wednesday Thursday Friday Saturday Sunday

Integers that represent 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 that represent the months: January is1, February is2, 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 DateTimeor DateTimeDelta instances obj1 and obj2, and returns -1,0, or 1, like built-in function cmp. It returns 0 (meaning that obj1 and obj2 are "equal") if the two instants or durations differ by less than accuracy seconds.


12.7.5. Submodules

Package mx.DateTimealso supplies several submodules for specialized purposes.Module mx.DateTime.ISO supplies functions to parse and generate date and time strings in ISO8601 format. Module mx.DateTime.ARPA supplies functions to parse and generate date and time strings in ARPA format, as 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: 2004
Pages: 192
Authors: Alex Martelli

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