14
14
The :mod:`datetime` module supplies classes for manipulating dates and times in
15
15
both simple and complex ways. While date and time arithmetic is supported, the
16
focus of the implementation is on efficient member extraction for output
16
focus of the implementation is on efficient attribute extraction for output
17
17
formatting and manipulation. For related
18
18
functionality, see also the :mod:`time` and :mod:`calendar` modules.
20
20
There are two kinds of date and time objects: "naive" and "aware". This
21
21
distinction refers to whether the object has any notion of time zone, daylight
22
22
saving time, or other kind of algorithmic or political time adjustment. Whether
23
a naive :class:`datetime` object represents Coordinated Universal Time (UTC),
23
a naive :class:`.datetime` object represents Coordinated Universal Time (UTC),
24
24
local time, or time in some other timezone is purely up to the program, just
25
25
like it's up to the program whether a particular number represents metres,
26
miles, or mass. Naive :class:`datetime` objects are easy to understand and to
26
miles, or mass. Naive :class:`.datetime` objects are easy to understand and to
27
27
work with, at the cost of ignoring some aspects of reality.
29
For applications requiring more, :class:`datetime` and :class:`time` objects
30
have an optional time zone information member, :attr:`tzinfo`, that can contain
31
an instance of a subclass of the abstract :class:`tzinfo` class. These
29
For applications requiring more, :class:`.datetime` and :class:`.time` objects
30
have an optional time zone information attribute, :attr:`tzinfo`, that can be
31
set to an instance of a subclass of the abstract :class:`tzinfo` class. These
32
32
:class:`tzinfo` objects capture information about the offset from UTC time, the
33
33
time zone name, and whether Daylight Saving Time is in effect. Note that no
34
34
concrete :class:`tzinfo` classes are supplied by the :mod:`datetime` module.
669
669
``tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))``.
671
671
:meth:`fromtimestamp` may raise :exc:`ValueError`, if the timestamp is out of
672
the range of values supported by the platform C :cfunc:`localtime` or
673
:cfunc:`gmtime` functions. It's common for this to be restricted to years in
672
the range of values supported by the platform C :c:func:`localtime` or
673
:c:func:`gmtime` functions. It's common for this to be restricted to years in
674
674
1970 through 2038. Note that on non-POSIX systems that include leap seconds in
675
675
their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`,
676
676
and then it's possible to have two timestamps differing by a second that yield
677
identical :class:`datetime` objects. See also :meth:`utcfromtimestamp`.
677
identical :class:`.datetime` objects. See also :meth:`utcfromtimestamp`.
680
680
.. classmethod:: datetime.utcfromtimestamp(timestamp)
682
Return the UTC :class:`datetime` corresponding to the POSIX timestamp, with
682
Return the UTC :class:`.datetime` corresponding to the POSIX timestamp, with
683
683
:attr:`tzinfo` ``None``. This may raise :exc:`ValueError`, if the timestamp is
684
out of the range of values supported by the platform C :cfunc:`gmtime` function.
684
out of the range of values supported by the platform C :c:func:`gmtime` function.
685
685
It's common for this to be restricted to years in 1970 through 2038. See also
686
686
:meth:`fromtimestamp`.
689
689
.. classmethod:: datetime.fromordinal(ordinal)
691
Return the :class:`datetime` corresponding to the proleptic Gregorian ordinal,
691
Return the :class:`.datetime` corresponding to the proleptic Gregorian ordinal,
692
692
where January 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1
693
693
<= ordinal <= datetime.max.toordinal()``. The hour, minute, second and
694
694
microsecond of the result are all 0, and :attr:`tzinfo` is ``None``.
697
697
.. classmethod:: datetime.combine(date, time)
699
Return a new :class:`datetime` object whose date members are equal to the given
700
:class:`date` object's, and whose time and :attr:`tzinfo` members are equal to
701
the given :class:`time` object's. For any :class:`datetime` object *d*, ``d ==
702
datetime.combine(d.date(), d.timetz())``. If date is a :class:`datetime`
703
object, its time and :attr:`tzinfo` members are ignored.
699
Return a new :class:`.datetime` object whose date components are equal to the
700
given :class:`date` object's, and whose time components and :attr:`tzinfo`
701
attributes are equal to the given :class:`.time` object's. For any
702
:class:`.datetime` object *d*,
703
``d == datetime.combine(d.date(), d.timetz())``. If date is a
704
:class:`.datetime` object, its time components and :attr:`tzinfo` attributes
706
708
.. classmethod:: datetime.strptime(date_string, format)
708
Return a :class:`datetime` corresponding to *date_string*, parsed according to
710
Return a :class:`.datetime` corresponding to *date_string*, parsed according to
709
711
*format*. This is equivalent to ``datetime(*(time.strptime(date_string,
710
712
format)[0:6]))``. :exc:`ValueError` is raised if the date_string and format
711
713
can't be parsed by :func:`time.strptime` or if it returns a value which isn't a
719
721
.. attribute:: datetime.min
721
The earliest representable :class:`datetime`, ``datetime(MINYEAR, 1, 1,
723
The earliest representable :class:`.datetime`, ``datetime(MINYEAR, 1, 1,
725
727
.. attribute:: datetime.max
727
The latest representable :class:`datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59,
729
The latest representable :class:`.datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59,
728
730
59, 999999, tzinfo=None)``.
731
733
.. attribute:: datetime.resolution
733
The smallest possible difference between non-equal :class:`datetime` objects,
735
The smallest possible difference between non-equal :class:`.datetime` objects,
734
736
``timedelta(microseconds=1)``.
774
776
.. attribute:: datetime.tzinfo
776
The object passed as the *tzinfo* argument to the :class:`datetime` constructor,
778
The object passed as the *tzinfo* argument to the :class:`.datetime` constructor,
777
779
or ``None`` if none was passed.
780
782
Supported operations:
782
+---------------------------------------+-------------------------------+
783
| Operation | Result |
784
+=======================================+===============================+
785
| ``datetime2 = datetime1 + timedelta`` | \(1) |
786
+---------------------------------------+-------------------------------+
787
| ``datetime2 = datetime1 - timedelta`` | \(2) |
788
+---------------------------------------+-------------------------------+
789
| ``timedelta = datetime1 - datetime2`` | \(3) |
790
+---------------------------------------+-------------------------------+
791
| ``datetime1 < datetime2`` | Compares :class:`datetime` to |
792
| | :class:`datetime`. (4) |
793
+---------------------------------------+-------------------------------+
784
+---------------------------------------+--------------------------------+
785
| Operation | Result |
786
+=======================================+================================+
787
| ``datetime2 = datetime1 + timedelta`` | \(1) |
788
+---------------------------------------+--------------------------------+
789
| ``datetime2 = datetime1 - timedelta`` | \(2) |
790
+---------------------------------------+--------------------------------+
791
| ``timedelta = datetime1 - datetime2`` | \(3) |
792
+---------------------------------------+--------------------------------+
793
| ``datetime1 < datetime2`` | Compares :class:`.datetime` to |
794
| | :class:`.datetime`. (4) |
795
+---------------------------------------+--------------------------------+
796
798
datetime2 is a duration of timedelta removed from datetime1, moving forward in
797
799
time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0. The
798
result has the same :attr:`tzinfo` member as the input datetime, and datetime2 -
799
datetime1 == timedelta after. :exc:`OverflowError` is raised if datetime2.year
800
would be smaller than :const:`MINYEAR` or larger than :const:`MAXYEAR`. Note
801
that no time zone adjustments are done even if the input is an aware object.
800
result has the same :attr:`tzinfo` attribute as the input datetime, and
801
datetime2 - datetime1 == timedelta after. :exc:`OverflowError` is raised if
802
datetime2.year would be smaller than :const:`MINYEAR` or larger than
803
:const:`MAXYEAR`. Note that no time zone adjustments are done even if the
804
input is an aware object.
804
807
Computes the datetime2 such that datetime2 + timedelta == datetime1. As for
805
addition, the result has the same :attr:`tzinfo` member as the input datetime,
806
and no time zone adjustments are done even if the input is aware. This isn't
807
quite equivalent to datetime1 + (-timedelta), because -timedelta in isolation
808
can overflow in cases where datetime1 - timedelta does not.
808
addition, the result has the same :attr:`tzinfo` attribute as the input
809
datetime, and no time zone adjustments are done even if the input is aware.
810
This isn't quite equivalent to datetime1 + (-timedelta), because -timedelta
811
in isolation can overflow in cases where datetime1 - timedelta does not.
811
Subtraction of a :class:`datetime` from a :class:`datetime` is defined only if
814
Subtraction of a :class:`.datetime` from a :class:`.datetime` is defined only if
812
815
both operands are naive, or if both are aware. If one is aware and the other is
813
816
naive, :exc:`TypeError` is raised.
815
If both are naive, or both are aware and have the same :attr:`tzinfo` member,
816
the :attr:`tzinfo` members are ignored, and the result is a :class:`timedelta`
818
If both are naive, or both are aware and have the same :attr:`tzinfo` attribute,
819
the :attr:`tzinfo` attributes are ignored, and the result is a :class:`timedelta`
817
820
object *t* such that ``datetime2 + t == datetime1``. No time zone adjustments
818
821
are done in this case.
820
If both are aware and have different :attr:`tzinfo` members, ``a-b`` acts as if
821
*a* and *b* were first converted to naive UTC datetimes first. The result is
822
``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None) -
823
b.utcoffset())`` except that the implementation never overflows.
823
If both are aware and have different :attr:`tzinfo` attributes, ``a-b`` acts
824
as if *a* and *b* were first converted to naive UTC datetimes first. The
825
result is ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None)
826
- b.utcoffset())`` except that the implementation never overflows.
826
829
*datetime1* is considered less than *datetime2* when *datetime1* precedes
827
830
*datetime2* in time.
829
832
If one comparand is naive and the other is aware, :exc:`TypeError` is raised.
830
If both comparands are aware, and have the same :attr:`tzinfo` member, the
831
common :attr:`tzinfo` member is ignored and the base datetimes are compared. If
832
both comparands are aware and have different :attr:`tzinfo` members, the
833
comparands are first adjusted by subtracting their UTC offsets (obtained from
834
``self.utcoffset()``).
833
If both comparands are aware, and have the same :attr:`tzinfo` attribute, the
834
common :attr:`tzinfo` attribute is ignored and the base datetimes are
835
compared. If both comparands are aware and have different :attr:`tzinfo`
836
attributes, the comparands are first adjusted by subtracting their UTC
837
offsets (obtained from ``self.utcoffset()``).
838
841
In order to stop comparison from falling back to the default scheme of comparing
839
842
object addresses, datetime comparison normally raises :exc:`TypeError` if the
840
other comparand isn't also a :class:`datetime` object. However,
843
other comparand isn't also a :class:`.datetime` object. However,
841
844
``NotImplemented`` is returned instead if the other comparand has a
842
845
:meth:`timetuple` attribute. This hook gives other kinds of date objects a
843
chance at implementing mixed-type comparison. If not, when a :class:`datetime`
846
chance at implementing mixed-type comparison. If not, when a :class:`.datetime`
844
847
object is compared to an object of a different type, :exc:`TypeError` is raised
845
848
unless the comparison is ``==`` or ``!=``. The latter cases return
846
849
:const:`False` or :const:`True`, respectively.
848
:class:`datetime` objects can be used as dictionary keys. In Boolean contexts,
849
all :class:`datetime` objects are considered to be true.
851
:class:`.datetime` objects can be used as dictionary keys. In Boolean contexts,
852
all :class:`.datetime` objects are considered to be true.
851
854
Instance methods:
858
861
.. method:: datetime.time()
860
Return :class:`time` object with same hour, minute, second and microsecond.
863
Return :class:`.time` object with same hour, minute, second and microsecond.
861
864
:attr:`tzinfo` is ``None``. See also method :meth:`timetz`.
864
867
.. method:: datetime.timetz()
866
Return :class:`time` object with same hour, minute, second, microsecond, and
867
tzinfo members. See also method :meth:`time`.
869
Return :class:`.time` object with same hour, minute, second, microsecond, and
870
tzinfo attributes. See also method :meth:`time`.
870
873
.. method:: datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
872
Return a datetime with the same members, except for those members given new
873
values by whichever keyword arguments are specified. Note that ``tzinfo=None``
874
can be specified to create a naive datetime from an aware datetime with no
875
conversion of date and time members.
875
Return a datetime with the same attributes, except for those attributes given
876
new values by whichever keyword arguments are specified. Note that
877
``tzinfo=None`` can be specified to create a naive datetime from an aware
878
datetime with no conversion of date and time data.
878
881
.. method:: datetime.astimezone(tz)
880
Return a :class:`datetime` object with new :attr:`tzinfo` member *tz*, adjusting
881
the date and time members so the result is the same UTC time as *self*, but in
883
Return a :class:`.datetime` object with new :attr:`tzinfo` attribute *tz*,
884
adjusting the date and time data so the result is the same UTC time as
885
*self*, but in *tz*'s local time.
884
887
*tz* must be an instance of a :class:`tzinfo` subclass, and its
885
888
:meth:`utcoffset` and :meth:`dst` methods must not return ``None``. *self* must
887
890
not return ``None``).
889
892
If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no
890
adjustment of date or time members is performed. Else the result is local time
891
in time zone *tz*, representing the same UTC time as *self*: after ``astz =
892
dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will usually have the same date
893
and time members as ``dt - dt.utcoffset()``. The discussion of class
894
:class:`tzinfo` explains the cases at Daylight Saving Time transition boundaries
895
where this cannot be achieved (an issue only if *tz* models both standard and
893
adjustment of date or time data is performed. Else the result is local
894
time in time zone *tz*, representing the same UTC time as *self*: after
895
``astz = dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will usually have
896
the same date and time data as ``dt - dt.utcoffset()``. The discussion
897
of class :class:`tzinfo` explains the cases at Daylight Saving Time transition
898
boundaries where this cannot be achieved (an issue only if *tz* models both
899
standard and daylight time).
898
901
If you merely want to attach a time zone object *tz* to a datetime *dt* without
899
adjustment of date and time members, use ``dt.replace(tzinfo=tz)``. If you
902
adjustment of date and time data, use ``dt.replace(tzinfo=tz)``. If you
900
903
merely want to remove the time zone object from an aware datetime *dt* without
901
conversion of date and time members, use ``dt.replace(tzinfo=None)``.
904
conversion of date and time data, use ``dt.replace(tzinfo=None)``.
903
906
Note that the default :meth:`tzinfo.fromutc` method can be overridden in a
904
907
:class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`.
1162
1165
.. attribute:: time.min
1164
The earliest representable :class:`time`, ``time(0, 0, 0, 0)``.
1167
The earliest representable :class:`.time`, ``time(0, 0, 0, 0)``.
1167
1170
.. attribute:: time.max
1169
The latest representable :class:`time`, ``time(23, 59, 59, 999999)``.
1172
The latest representable :class:`.time`, ``time(23, 59, 59, 999999)``.
1172
1175
.. attribute:: time.resolution
1174
The smallest possible difference between non-equal :class:`time` objects,
1175
``timedelta(microseconds=1)``, although note that arithmetic on :class:`time`
1176
objects is not supported.
1177
The smallest possible difference between non-equal :class:`.time` objects,
1178
``timedelta(microseconds=1)``, although note that arithmetic on
1179
:class:`.time` objects is not supported.
1179
1182
Instance attributes (read-only):
1201
1204
.. attribute:: time.tzinfo
1203
The object passed as the tzinfo argument to the :class:`time` constructor, or
1206
The object passed as the tzinfo argument to the :class:`.time` constructor, or
1204
1207
``None`` if none was passed.
1207
1210
Supported operations:
1209
* comparison of :class:`time` to :class:`time`, where *a* is considered less
1212
* comparison of :class:`.time` to :class:`.time`, where *a* is considered less
1210
1213
than *b* when *a* precedes *b* in time. If one comparand is naive and the other
1211
1214
is aware, :exc:`TypeError` is raised. If both comparands are aware, and have
1212
the same :attr:`tzinfo` member, the common :attr:`tzinfo` member is ignored and
1213
the base times are compared. If both comparands are aware and have different
1214
:attr:`tzinfo` members, the comparands are first adjusted by subtracting their
1215
UTC offsets (obtained from ``self.utcoffset()``). In order to stop mixed-type
1216
comparisons from falling back to the default comparison by object address, when
1217
a :class:`time` object is compared to an object of a different type,
1218
:exc:`TypeError` is raised unless the comparison is ``==`` or ``!=``. The
1219
latter cases return :const:`False` or :const:`True`, respectively.
1215
the same :attr:`tzinfo` attribute, the common :attr:`tzinfo` attribute is
1216
ignored and the base times are compared. If both comparands are aware and
1217
have different :attr:`tzinfo` attributes, the comparands are first adjusted by
1218
subtracting their UTC offsets (obtained from ``self.utcoffset()``). In order
1219
to stop mixed-type comparisons from falling back to the default comparison by
1220
object address, when a :class:`.time` object is compared to an object of a
1221
different type, :exc:`TypeError` is raised unless the comparison is ``==`` or
1222
``!=``. The latter cases return :const:`False` or :const:`True`, respectively.
1221
1224
* hash, use as dict key
1223
1226
* efficient pickling
1225
* in Boolean contexts, a :class:`time` object is considered to be true if and
1228
* in Boolean contexts, a :class:`.time` object is considered to be true if and
1226
1229
only if, after converting it to minutes and subtracting :meth:`utcoffset` (or
1227
1230
``0`` if that's ``None``), the result is non-zero.
1362
1365
already been added to the UTC offset returned by :meth:`utcoffset`, so there's
1363
1366
no need to consult :meth:`dst` unless you're interested in obtaining DST info
1364
1367
separately. For example, :meth:`datetime.timetuple` calls its :attr:`tzinfo`
1365
member's :meth:`dst` method to determine how the :attr:`tm_isdst` flag should be
1366
set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for DST changes
1367
when crossing time zones.
1368
attribute's :meth:`dst` method to determine how the :attr:`tm_isdst` flag
1369
should be set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for
1370
DST changes when crossing time zones.
1369
1372
An instance *tz* of a :class:`tzinfo` subclass that models both standard and
1370
1373
daylight times must be consistent in this sense:
1372
1375
``tz.utcoffset(dt) - tz.dst(dt)``
1374
must return the same result for every :class:`datetime` *dt* with ``dt.tzinfo ==
1377
must return the same result for every :class:`.datetime` *dt* with ``dt.tzinfo ==
1375
1378
tz`` For sane :class:`tzinfo` subclasses, this expression yields the time
1376
1379
zone's "standard offset", which should not depend on the date or the time, but
1377
1380
only on geographic location. The implementation of :meth:`datetime.astimezone`
1524
1527
:meth:`strftime` and :meth:`strptime` Behavior
1525
1528
----------------------------------------------
1527
:class:`date`, :class:`datetime`, and :class:`time` objects all support a
1530
:class:`date`, :class:`.datetime`, and :class:`.time` objects all support a
1528
1531
``strftime(format)`` method, to create a string representing the time under the
1529
1532
control of an explicit format string. Broadly speaking, ``d.strftime(fmt)``
1530
1533
acts like the :mod:`time` module's ``time.strftime(fmt, d.timetuple())``
1531
1534
although not all objects support a :meth:`timetuple` method.
1533
1536
Conversely, the :meth:`datetime.strptime` class method creates a
1534
:class:`datetime` object from a string representing a date and time and a
1537
:class:`.datetime` object from a string representing a date and time and a
1535
1538
corresponding format string. ``datetime.strptime(date_string, format)`` is
1536
1539
equivalent to ``datetime(*(time.strptime(date_string, format)[0:6]))``.
1538
For :class:`time` objects, the format codes for year, month, and day should not
1541
For :class:`.time` objects, the format codes for year, month, and day should not
1539
1542
be used, as time objects have no such values. If they're used anyway, ``1900``
1540
1543
is substituted for the year, and ``1`` for the month and day.