Previous Page
Next Page

12.2. The datetime Module

datetime provides classes representing date and time objects, which can be either aware of time zones or naïve (the default). Class tzinfo is abstract: module datetime supplies no implementation (for all the gory details, see http://docs.python.org/lib/datetime-tzinfo.html). (See module pytz, in "The pytz Module" on page 313, for a good, simple implementation of tzinfo, which lets you easily create aware objects.) All the types in module datetime have immutable instances, so the instances' attributes are all read-only and the instances can be keys in a dict or items in a set.

12.2.1. Class date

Class date instances represent a date (no time of day in particular within that date), are always naïve, and assume the Gregorian calendar was always in effect. date instances have three read-only integer attributes: year, month, and day.

date

date(year,month,day)

Class date also supplies some class methods usable as alternative constructors.

fromordinal

date.fromordinal(ordinal)

Returns a date object corresponding to the proleptic Gregorian ordinal ordinal, where a value of 1 corresponds to the first day of the year 1.

fromtimestamp

date.fromtimestamp(timestamp)

Returns a date object corresponding to the instant timestamp expressed in seconds since the epoch.

today

date.today( )

Returns a date object representing today's date.

Instances of class date support some arithmetic: the difference between date instances is a timedelta instance, and you can add or subtract a date instance and a timedelta instance to construct another date instance. You can also compare any two instances of class date (the one that's later in time is considered greater).

An instance d of class date also supplies the following methods.

ctime

d.ctime( )

Returns a string representing date d in the same 24-character format as time.ctime.

isocalendar

d.isocalendar( )

Returns a tuple with three integers (ISO year, ISO week number, and ISO weekday). See http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm for more details about the ISO (International Standards Organization) calendar.

isoformat

d.isoformat( )

Returns a string representing date d in the format 'YYYY-MM-DD'; same as str(d).

isoweekday

d.isoweekday( )

Returns the day of the week of date d as an integer; 1 for Monday through 7 for Sunday.

replace

d.replace(year=None,month=None,day=None)

Returns a new date object, like d except for those attributes explicitly specified as arguments, which get replaced. For example:

date(x,y,z).replace(month=m) == date(x,m,z)

strftime

d.strftime( )

Returns a string representing date d as specified by string fmt, like:

time.strftime(fmt, d.totuple( ))

timetuple

d.timetuple( )

Returns a time tuple corresponding to date d at time 00:00:00 (midnight).

toordinal

d.toordinal( )

Returns the proleptic Gregorian ordinal corresponding to date d. For example:

date(1,1,1).toordinal( ) == 1

weekday

d.weekday( )

Returns the day of the week of date d as an integer; 0 for Monday through 6 for Sunday.


12.2.2. Class time

Class time instances represent a time of day (of no particular date), may be naïve or aware regarding time zones, and always ignore leap seconds. They have five attributes: four read-only integers (hour, minute, second, and microsecond) and an optional tzinfo (None for naïve instances).

time

time(hour=0,minute=0,second=0,microsecond=0,tzinfo=None)

Instances of class time do not support arithmetic. You can compare two instances of class time (the one that's later in time is considered greater), but only if they are either both aware or both naïve.

An instance t of class time also supplies the following methods.

isoformat

t.isoformat( )

Returns a string representing time t in the format 'HH:MM:SS'; same as str(t). If t.microsecond!=0, the resulting string is longer: 'HH:MM:SS.mmmmmm'. If t is aware, six more characters, '+HH:MM', are added at the end to represent the time zone's offset from UTC. In other words, this formatting operation follows the ISO1601 standard.

replace

t.replace(hour=None,minute=None,second=None,microsecond=None[,tzinfo])

Returns a new time object, like t except for those attributes explicitly specified as arguments, which get replaced. For example:

time(x,y,z).replace(minute=m) == time(x,m,z)

strftime

t.strftime( )

Returns a string representing time t as specified by string fmt.

An instance t of class time also supplies methods dst, tzname, and utcoffset, which delegate to t.tzinfo, but return None if t.tzinfo is None.


12.2.3. Class datetime

Class datetime instances represent an instant (a date, with a specific time of day within that date), may be naïve or aware regarding time zones, and always ignore leap seconds. Class datetime subclasses date and adds time's attributes; its instances have read-only integers year, month, day, hour, minute, second, and microsecond, and an optional tzinfo (None for naïve instances).

datetime

datetime(year,month,day,hour=0,minute=0,second=0,microsecond=0,tzinfo=None)

Class datetime also supplies some class methods usable as alternative constructors.

combine

datetime.combine(date,time)

Returns a datetime object with the date attributes taken from date and the time attributes (including tzinfo) taken from time. datetime.combine(d,t) is like:

datetime(d.year, d.month, d.day,
         t.hour, t.minute, t.second, t.microsecond,
t.tzinfo)

fromordinal

datetime.fromordinal(ordinal)

Returns a datetime object corresponding to the date given proleptic Gregorian ordinal ordinal, where a value of 1 corresponds to the first day of the year 1, at midnight.

fromtimestamp

datetime.fromtimestamp(timestamp,tz=None)

Returns a datetime object corresponding to the instant timestamp expressed in seconds since the epoch, in local time. When tz is not None, returns an aware datetime object with the given tzinfo instance tz.

now

datetime.now(tz=None)

Returns a datetime object representing the current local date and time. When tz is not None, returns an aware datetime object with the given tzinfo instance tz.

today

datetime.today( )

Returns a datetime object representing the current local date and time.

utcfromtime-stamp

datetime.utcfromtimestamp(timestamp)

Returns a naive datetime object corresponding to the instant timestamp expressed in seconds since the epoch, in UTC.

utcnow

datetime.utcnow( )

Returns a datetime object representing the current date and time, in UTC.

Instances of class datetime support some arithmetic: the difference between datetime instances is a timedelta instance, and you can add or subtract a datetime instance and a timedelta instance to construct another datetime instance. You can compare two instances of class datetime (the one that's later in time is considered greater), but only if they are either both aware or both naïve. An instance d of class datetime also supplies the following methods.

astimezone

d.timezone(tz)

Returns a new aware datetime object, like d (which must also be aware), except that the time zone is converted to the one in tzinfo object tz. Note that d.astimezone(tz) is different from d.replace(tzinfo=tz): the latter does no conversion but rather just copies all of d's attributes except for d.tzinfo.

ctime

d.ctime( )

Returns a string representing date d in the same 24-character format as time.ctime.

date

d.date( )

Returns a date object representing the same date as d.

isocalendar

d.isocalendar( )

Returns a tuple with three integers (ISO year, ISO week number, and ISO weekday) for d's date. See http://www.phys.uu.nl/~vgent/calendar/isocalendar.htm for more details about the ISO (International Standards Organization) calendar.

isoformat

d.isoformat(sep='T')

Returns a string representing d in the format 'YYYY-MM-DDxHH:MM:SS', where x is the value of argument sep (must be a string of length 1). If d.microsecond!=0, seven characters, '.mmmmmm', are added after the 'SS' part of the string. If t is aware, six more characters, '+HH:MM', are added at the end to represent the time zone's offset from UTC. In other words, this formatting operation follows the ISO1601 standard. str(d) is the same as d.isoformat(' ').

isoweekday

d.isoweekday( )

Returns the day of the week of d's date as an integer; 1 for Monday through 7 for Sunday.

replace

d.replace(year=None,month=None,day=None,hour=None,minute=None,second=None,microsecond=None[,tzinfo])

Returns a new datetime object, like d except for those attributes explicitly specified as arguments, which get replaced. For example:

datetime(x,y,z).replace(month=m) == datetime(x,m,z)

strftime

d.strftime( )

Returns a string representing d as specified by string fmt, such as:

time.strftime(fmt, d.totuple( ))

time

d.time( )

Returns a naïve time object representing the same time of day as d.

timetz

d.timetz( )

Returns a time object representing the same time of day as d, with the same tzinfo.

timetuple

d.timetuple( )

Returns a time-tuple corresponding to instant d.

toordinal

d.toordinal( )

Returns the proleptic Gregorian ordinal corresponding to d's date. For example:

datetime(1,1,1).toordinal( ) == 1

utctimetuple

d.utctimetuple( )

Returns a time-tuple corresponding to instant d; normalized to UTC if d is aware.

weekday

d.weekday( )

Returns the day of the week of d's date as an integer; 0 for Monday through 6 for Sunday.

An instance d of class datetime also supplies methods dst, tzname, and utcoffset, which delegate to d.tzinfo, but return None if d.tzinfo is None.


12.2.4. Class timedelta

Class timedelta instances represent time intervals with three read-only integer attributes: days, seconds, and microseconds.

timedelta

timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

Converts all units with the obvious factors (a week is 7 days, an hour is 3,600 seconds, and so on) and normalizes everything to the three integer attributes, ensuring that 0<=seconds<3600*24 and 0<=microseconds<1000000. For example:

print repr(timedelta(minutes=0.5)) # emits datetime.timedelta(0, 30)
print repr(timedelta(minutes=0.5)) # emits datetime.timedelta(-1, 82800)

Instances of class timedelta support arithmetic (between themselves, with integers, and with instances of classes date and datetime) and comparisons between themselves. To compute from a timedelta instance t the equivalent time interval as a floating-point number of seconds, use:

t.days*86400+t.seconds+t.microseconds/1000000.0



Previous Page
Next Page