6.10.4 datetime Objects

##
6.10.4 `datetime` Objects

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:

class `datetime`( | year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])

  The year, month and day arguments are required. tzinfo may be `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:

`today`( | )

  Return the current local datetime, with `tzinfo` `None`. This is equivalent to `datetime.fromtimestamp(time.time())`. See also `now()`, `fromtimestamp()`.

`now`( | [tz])

  Return the current local date and time. If optional argument tz is `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()`.

`utcnow`( | )

  Return the current UTC date and time, with `tzinfo` `None`. This is like `now()`, but returns the current UTC date and time, as a naive `datetime` object. See also `now()`.

`fromtimestamp`( | timestamp[, tz])

  Return the local date and time corresponding to the POSIX timestamp, such as is returned by `time.time()`. If optional argument tz is `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()`.

`utcfromtimestamp`( | timestamp)

  Return the UTC `datetime` corresponding to the POSIX timestamp, with `tzinfo` `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()`.

`fromordinal`( | ordinal)

  Return the `datetime` corresponding to the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1. `ValueError` is raised unless `1 <= ordinal <= datetime.max.toordinal()`. The hour, minute, second and microsecond of the result are all 0, and `tzinfo` is `None`.

`combine`( | date, time)

  Return a new `datetime` object whose date members are equal to the given `date` object's, and whose time and `tzinfo` members are equal to the given `time` object's. For any `datetime` object d, `d == datetime.combine(d.date(), d.timetz())`. If date is a `datetime` object, its time and `tzinfo` members are ignored.

Class attributes:

`min`
  The earliest representable `datetime`, `datetime(MINYEAR, 1, 1, tzinfo=None)`.

`max`
  The latest representable `datetime`, `datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, tzinfo=None)`.

`resolution`
  The smallest possible difference between non-equal `datetime` objects, `timedelta(microseconds=1)`.

Instance attributes (read-only):

`year`
  Between `MINYEAR` and `MAXYEAR` inclusive.

`month`
  Between 1 and 12 inclusive.

`day`
  Between 1 and the number of days in the given month of the given year.

`hour`
  In `range(24)`.

`minute`
  In `range(60)`.

`second`
  In `range(60)`.

`microsecond`
  In `range(1000000)`.

`tzinfo`
  The object passed as the tzinfo argument to the `datetime` constructor, or `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)

(1)

  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.

(2)
  Computes the datetime2 such that datetime2 + timedelta == datetime1. As for addition, the result has the same `tzinfo` member as the input datetime, and no time zone adjustments are done even if the input is aware. This isn't quite equivalent to datetime1 + (-timedelta), because -timedelta in isolation can overflow in cases where datetime1 - timedelta does not.

(3)
  Subtraction of a `datetime` from a `datetime` is defined only if both operands are naive, or if both are aware. If one is aware and the other is naive, `TypeError` is raised.

  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.

(4)

  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:

`date`( | )

  Return `date` object with same year, month and day.

`time`( | )

  Return `time` object with same hour, minute, second and microsecond. `tzinfo` is `None`. See also method `timetz()`.

`timetz`( | )

  Return `time` object with same hour, minute, second, microsecond, and tzinfo members. See also method `time()`.

`replace`( | [year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])

  Return a datetime with the same members, except for those members given new values by whichever keyword arguments are specified. Note that `tzinfo=None` can be specified to create a naive datetime from an aware datetime with no conversion of date and time members.

`astimezone`( | tz)

  Return a `datetime` object with new `tzinfo` member tz, adjusting the date and time members so the result is the same UTC time as self, but in tz's local time.

  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)

`utcoffset`( | )

  If `tzinfo` is `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.

`dst`( | )

  If `tzinfo` is `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.

`tzname`( | )

  If `tzinfo` is `None`, returns `None`, else returns `self.tzinfo.tzname(self)`, raises an exception if the latter doesn't return `None` or a string object,

`timetuple`( | )

  Return a `time.struct_time` such as returned by `time.localtime()`. `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`.

`utctimetuple`( | )

  If `datetime` instance d is naive, this is the same as `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.

`toordinal`( | )

  Return the proleptic Gregorian ordinal of the date. The same as `self.date().toordinal()`.

`weekday`( | )

  Return the day of the week as an integer, where Monday is 0 and Sunday is 6. The same as `self.date().weekday()`. See also `isoweekday()`.

`isoweekday`( | )

  Return the day of the week as an integer, where Monday is 1 and Sunday is 7. The same as `self.date().isoweekday()`. See also `weekday()`, `isocalendar()`.

`isocalendar`( | )

  Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The same as `self.date().isocalendar()`.

`isoformat`( | [sep])

  Return a string representing the date and time in ISO 8601 format, YYYY-MM-DDTHH:MM:SS.mmmmmm or, if `microsecond` is 0, YYYY-MM-DDTHH:MM:SS

  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__`( | )

  For a `datetime` instance d, `str(d)` is equivalent to `d.isoformat(' ')`.

`ctime`( | )

  Return a string representing the date and time, for example `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.

`strftime`( | format)

  Return a string representing the date and time, controlled by an explicit format string. See the section on `strftime()` behavior.