A datetime object is a single object containing all the information from a date object and a time object. Like a date object, datetime assumes the current Gregorian calendar extended in both directions; like a time object, datetime assumes there are exactly 3600*24 seconds in every day.
Constructor:
year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]) |
None
, or an instance of a tzinfo subclass. The
remaining arguments may be ints or longs, in the following ranges:
MINYEAR <= year <= MAXYEAR
1 <= month <= 12
1 <= day <= number of days in the given month and year
0 <= hour < 24
0 <= minute < 60
0 <= second < 60
0 <= microsecond < 1000000
If an argument outside those ranges is given, ValueError is raised.
Other constructors, all class methods:
) |
None
.
This is equivalent to
datetime.fromtimestamp(time.time())
.
See also now(), fromtimestamp().
[tz]) |
None
or not specified, this is like
today(), but, if possible, supplies more precision than can
be gotten from going through a time.time() timestamp (for
example, this may be possible on platforms supplying the C
gettimeofday() function).
Else tz must be an instance of a class tzinfo subclass,
and the current date and time are converted to tz's time
zone. In this case the result is equivalent to
tz.fromutc(datetime.utcnow().replace(tzinfo=tz))
.
See also today(), utcnow().
) |
None
.
This is like now(), but returns the current UTC date and time,
as a naive datetime object.
See also now().
timestamp[, tz]) |
None
or not specified, the
timestamp is converted to the platform's local date and time, and
the returned datetime object is naive.
Else tz must be an instance of a class tzinfo subclass,
and the timestamp is converted to tz's time zone. In this case
the result is equivalent to
tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))
.
fromtimestamp() may raise ValueError, if the timestamp is out of the range of values supported by the platform C localtime() or gmtime() functions. It's common for this to be restricted to years in 1970 through 2038. Note that on non-POSIX systems that include leap seconds in their notion of a timestamp, leap seconds are ignored by fromtimestamp(), and then it's possible to have two timestamps differing by a second that yield identical datetime objects. See also utcfromtimestamp().
timestamp) |
None
.
This may raise ValueError, if the
timestamp is out of the range of values supported by the platform
C gmtime() function. It's common for this to be
restricted to years in 1970 through 2038.
See also fromtimestamp().
ordinal) |
1 <= ordinal <=
datetime.max.toordinal()
. The hour, minute, second and
microsecond of the result are all 0,
and tzinfo is None
.
date, time) |
d ==
datetime.combine(d.date(), d.timetz())
. If date is a
datetime object, its time and tzinfo members are
ignored.
Class attributes:
datetime(MINYEAR, 1, 1, tzinfo=None)
.
datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, tzinfo=None)
.
timedelta(microseconds=1)
.
Instance attributes (read-only):
range(24)
.
range(60)
.
range(60)
.
range(1000000)
.
None
if none was passed.
Supported operations:
Operation | Result |
---|---|
datetime2 = datetime1 + timedelta |
(1) |
datetime2 = datetime1 - timedelta |
(2) |
timedelta = datetime1 - datetime2 |
(3) |
datetime1 < datetime2 |
Compares datetime to datetime. (4) |
datetime2 is a duration of timedelta removed from datetime1, moving
forward in time if timedelta.days
> 0, or backward if
timedelta.days
< 0. The result has the same tzinfo member
as the input datetime, and datetime2 - datetime1 == timedelta after.
OverflowError is raised if datetime2.year would be
smaller than MINYEAR or larger than MAXYEAR.
Note that no time zone adjustments are done even if the input is an
aware object.
If both are naive, or both are aware and have the same tzinfo
member, the tzinfo members are ignored, and the result is
a timedelta object t such that
datetime2 + t == datetime1
. No time zone
adjustments are done in this case.
If both are aware and have different tzinfo members,
a-b
acts as if a and b were first converted to
naive UTC datetimes first. The result is
(a.replace(tzinfo=None) - a.utcoffset()) -
(b.replace(tzinfo=None) - b.utcoffset())
except that the implementation never overflows.
datetime1 is considered less than datetime2 when datetime1 precedes datetime2 in time.
If one comparand is naive and
the other is aware, TypeError is raised. If both
comparands are aware, and have the same tzinfo member,
the common tzinfo member is ignored and the base datetimes
are compared. If both comparands are aware and have different
tzinfo members, the comparands are first adjusted by
subtracting their UTC offsets (obtained from self.utcoffset()
).
Note:
In order to stop comparison from falling back to the default
scheme of comparing object addresses, datetime comparison
normally raises TypeError if the other comparand
isn't also a datetime object. However,
NotImplemented
is returned instead if the other comparand
has a timetuple attribute. This hook gives other
kinds of date objects a chance at implementing mixed-type
comparison. If not, when a datetime object is
compared to an object of a different type, TypeError
is raised unless the comparison is ==
or !=
. The
latter cases return False or True,
respectively.
datetime objects can be used as dictionary keys. In Boolean contexts, all datetime objects are considered to be true.
Instance methods:
) |
) |
None
. See also method timetz().
) |
[year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]]) |
tzinfo=None
can be specified to create a naive datetime from
an aware datetime with no conversion of date and time members.
tz) |
tz must be an instance of a tzinfo subclass, and its
utcoffset() and dst() methods must not return
None
. self must be aware (self.tzinfo
must
not be None
, and self.utcoffset()
must not return
None
).
If self.tzinfo
is tz,
self.astimezone(tz)
is equal to self: no
adjustment of date or time members is performed.
Else the result is local time in time zone tz, representing the
same UTC time as self: after astz =
dt.astimezone(tz)
,
astz - astz.utcoffset()
will usually have the same
date and time members as dt - dt.utcoffset()
.
The discussion of class tzinfo explains the cases at Daylight
Saving Time transition boundaries where this cannot be achieved (an issue
only if tz models both standard and daylight time).
If you merely want to attach a time zone object tz to a
datetime dt without adjustment of date and time members,
use dt.replace(tzinfo=tz)
. If
you merely want to remove the time zone object from an aware datetime
dt without conversion of date and time members, use
dt.replace(tzinfo=None)
.
Note that the default tzinfo.fromutc() method can be overridden in a tzinfo subclass to affect the result returned by astimezone(). Ignoring error cases, astimezone() acts like:
def astimezone(self, tz): if self.tzinfo is tz: return self # Convert self to UTC, and attach the new time zone object. utc = (self - self.utcoffset()).replace(tzinfo=tz) # Convert from UTC to tz's local time. return tz.fromutc(utc)
) |
None
, returns None
, else
returns self.tzinfo.utcoffset(self)
, and
raises an exception if the latter doesn't return None
, or
a timedelta object representing a whole number of minutes
with magnitude less than one day.
) |
None
, returns None
, else
returns self.tzinfo.dst(self)
, and
raises an exception if the latter doesn't return None
, or
a timedelta object representing a whole number of minutes
with magnitude less than one day.
) |
None
, returns None
, else
returns self.tzinfo.tzname(self)
,
raises an exception if the latter doesn't return None
or
a string object,
) |
d.timetuple()
is equivalent to
time.struct_time((d.year, d.month, d.day,
d.hour, d.minute, d.second,
d.weekday(),
d.toordinal() - date(d.year, 1, 1).toordinal() + 1,
dst))
The tm_isdst flag of the result is set according to
the dst() method: tzinfo is None
or
dst() returns None
,
tm_isdst is set to -1
; else if dst() returns
a non-zero value, tm_isdst is set to 1
;
else tm_isdst
is set to 0
.
) |
d.timetuple()
except that tm_isdst is forced to 0
regardless of what d.dst()
returns. DST is never in effect
for a UTC time.
If d is aware, d is normalized to UTC time, by subtracting
d.utcoffset()
, and a time.struct_time for the
normalized time is returned. tm_isdst is forced to 0.
Note that the result's tm_year member may be
MINYEAR-1 or MAXYEAR+1, if d.year was
MINYEAR
or MAXYEAR
and UTC adjustment spills over a
year boundary.
) |
self.date().toordinal()
.
) |
self.date().weekday()
.
See also isoweekday().
) |
self.date().isoweekday()
.
See also weekday(), isocalendar().
) |
self.date().isocalendar()
.
[sep]) |
If utcoffset() does not return None
, a 6-character
string is appended, giving the UTC offset in (signed) hours and
minutes:
YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM
or, if microsecond is 0
YYYY-MM-DDTHH:MM:SS+HH:MM
The optional argument sep (default 'T'
) is a
one-character separator, placed between the date and time portions
of the result. For example,
>>> from datetime import tzinfo, timedelta, datetime >>> class TZ(tzinfo): ... def utcoffset(self, dt): return timedelta(minutes=-399) ... >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ') '2002-12-25 00:00:00-06:39'
) |
str(d)
is
equivalent to d.isoformat(' ')
.
) |
datetime(2002, 12, 4, 20, 30, 40).ctime() ==
'Wed Dec 4 20:30:40 2002'
.
d.ctime()
is equivalent to
time.ctime(time.mktime(d.timetuple()))
on platforms where
the native C ctime() function (which
time.ctime() invokes, but which
datetime.ctime() does not invoke) conforms to the C
standard.
format) |
See About this document... for information on suggesting changes.