Changeset 391 for python/trunk/Doc/library/datetime.rst
- Timestamp:
- Mar 19, 2014, 11:31:01 PM (11 years ago)
- Location:
- python/trunk
- Files:
-
- 2 edited
Legend:
- Unmodified
- Added
- Removed
-
python/trunk
-
Property svn:mergeinfo
set to
/python/vendor/Python-2.7.6 merged eligible /python/vendor/current merged eligible
-
Property svn:mergeinfo
set to
-
python/trunk/Doc/library/datetime.rst
r2 r391 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 17 formatting and manipulation. For related 18 functionality, see also the :mod:`time` and :mod:`calendar` modules. 19 20 There are two kinds of date and time objects: "naive" and "aware". This 21 distinction refers to whether the object has any notion of time zone, daylight 22 saving time, or other kind of algorithmic or political time adjustment. Whether 23 a naive :class:`datetime` object represents Coordinated Universal Time (UTC), 24 local time, or time in some other timezone is purely up to the program, just 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 27 work with, at the cost of ignoring some aspects of reality. 28 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 32 :class:`tzinfo` objects capture information about the offset from UTC time, the 33 time zone name, and whether Daylight Saving Time is in effect. Note that no 34 concrete :class:`tzinfo` classes are supplied by the :mod:`datetime` module. 35 Supporting timezones at whatever level of detail is required is up to the 36 application. The rules for time adjustment across the world are more political 37 than rational, and there is no standard suitable for every application. 16 focus of the implementation is on efficient attribute extraction for output 17 formatting and manipulation. For related functionality, see also the 18 :mod:`time` and :mod:`calendar` modules. 19 20 There are two kinds of date and time objects: "naive" and "aware". 21 22 An aware object has sufficient knowledge of applicable algorithmic and 23 political time adjustments, such as time zone and daylight saving time 24 information, to locate itself relative to other aware objects. An aware object 25 is used to represent a specific moment in time that is not open to 26 interpretation [#]_. 27 28 A naive object does not contain enough information to unambiguously locate 29 itself relative to other date/time objects. Whether a naive object represents 30 Coordinated Universal Time (UTC), local time, or time in some other timezone is 31 purely up to the program, just like it's up to the program whether a particular 32 number represents metres, miles, or mass. Naive objects are easy to understand 33 and to work with, at the cost of ignoring some aspects of reality. 34 35 For applications requiring aware objects, :class:`.datetime` and :class:`.time` 36 objects have an optional time zone information attribute, :attr:`tzinfo`, that 37 can be set to an instance of a subclass of the abstract :class:`tzinfo` class. 38 These :class:`tzinfo` objects capture information about the offset from UTC 39 time, the time zone name, and whether Daylight Saving Time is in effect. Note 40 that no concrete :class:`tzinfo` classes are supplied by the :mod:`datetime` 41 module. Supporting timezones at whatever level of detail is required is up to 42 the application. The rules for time adjustment across the world are more 43 political than rational, and there is no standard suitable for every 44 application. 38 45 39 46 The :mod:`datetime` module exports the following constants: 40 47 41 42 48 .. data:: MINYEAR 43 49 44 The smallest year number allowed in a :class:`date` or :class:` datetime` object.50 The smallest year number allowed in a :class:`date` or :class:`.datetime` object. 45 51 :const:`MINYEAR` is ``1``. 46 52 … … 48 54 .. data:: MAXYEAR 49 55 50 The largest year number allowed in a :class:`date` or :class:` datetime` object.56 The largest year number allowed in a :class:`date` or :class:`.datetime` object. 51 57 :const:`MAXYEAR` is ``9999``. 52 58 … … 63 69 Available Types 64 70 --------------- 65 66 71 67 72 .. class:: date … … 93 98 :noindex: 94 99 95 A duration expressing the difference between two :class:`date`, :class:` time`,96 or :class:` datetime` instances to microsecond resolution.100 A duration expressing the difference between two :class:`date`, :class:`.time`, 101 or :class:`.datetime` instances to microsecond resolution. 97 102 98 103 … … 100 105 101 106 An abstract base class for time zone information objects. These are used by the 102 :class:` datetime` and :class:`time` classes to provide a customizable notion of107 :class:`.datetime` and :class:`.time` classes to provide a customizable notion of 103 108 time adjustment (for example, to account for time zone and/or daylight saving 104 109 time). … … 108 113 Objects of the :class:`date` type are always naive. 109 114 110 An object *d* of type :class:`time` or :class:`datetime` may be naive or aware. 111 *d* is aware if ``d.tzinfo`` is not ``None`` and ``d.tzinfo.utcoffset(d)`` does 112 not return ``None``. If ``d.tzinfo`` is ``None``, or if ``d.tzinfo`` is not 113 ``None`` but ``d.tzinfo.utcoffset(d)`` returns ``None``, *d* is naive. 115 An object of type :class:`.time` or :class:`.datetime` may be naive or aware. 116 A :class:`.datetime` object *d* is aware if ``d.tzinfo`` is not ``None`` and 117 ``d.tzinfo.utcoffset(d)`` does not return ``None``. If ``d.tzinfo`` is 118 ``None``, or if ``d.tzinfo`` is not ``None`` but ``d.tzinfo.utcoffset(d)`` 119 returns ``None``, *d* is naive. A :class:`.time` object *t* is aware 120 if ``t.tzinfo`` is not ``None`` and ``t.tzinfo.utcoffset(None)`` does not return 121 ``None``. Otherwise, *t* is naive. 114 122 115 123 The distinction between naive and aware doesn't apply to :class:`timedelta` … … 134 142 dates or times. 135 143 136 137 144 .. class:: timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]]) 138 145 … … 171 178 (-1, 86399, 999999) 172 179 180 173 181 Class attributes are: 174 175 182 176 183 .. attribute:: timedelta.min … … 239 246 | | to -*t* when ``t.days < 0``. (2) | 240 247 +--------------------------------+-----------------------------------------------+ 248 | ``str(t)`` | Returns a string in the form | 249 | | ``[D day[s], ][H]H:MM:SS[.UUUUUU]``, where D | 250 | | is negative for negative ``t``. (5) | 251 +--------------------------------+-----------------------------------------------+ 252 | ``repr(t)`` | Returns a string in the form | 253 | | ``datetime.timedelta(D[, S[, U]])``, where D | 254 | | is negative for negative ``t``. (5) | 255 +--------------------------------+-----------------------------------------------+ 241 256 242 257 Notes: … … 254 269 -*timedelta.max* is not representable as a :class:`timedelta` object. 255 270 271 (5) 272 String representations of :class:`timedelta` objects are normalized 273 similarly to their internal representation. This leads to somewhat 274 unusual results for negative timedeltas. For example: 275 276 >>> timedelta(hours=-5) 277 datetime.timedelta(-1, 68400) 278 >>> print(_) 279 -1 day, 19:00:00 280 256 281 In addition to the operations listed above :class:`timedelta` objects support 257 certain additions and subtractions with :class:`date` and :class:` datetime`282 certain additions and subtractions with :class:`date` and :class:`.datetime` 258 283 objects (see below). 259 284 … … 270 295 considered to be true if and only if it isn't equal to ``timedelta(0)``. 271 296 297 Instance methods: 298 299 .. method:: timedelta.total_seconds() 300 301 Return the total number of seconds contained in the duration. 302 Equivalent to ``(td.microseconds + (td.seconds + td.days * 24 * 303 3600) * 10**6) / 10**6`` computed with true division enabled. 304 305 Note that for very large time intervals (greater than 270 years on 306 most platforms) this method will lose microsecond accuracy. 307 308 .. versionadded:: 2.7 309 310 272 311 Example usage: 273 312 … … 276 315 >>> another_year = timedelta(weeks=40, days=84, hours=23, 277 316 ... minutes=50, seconds=600) # adds up to 365 days 317 >>> year.total_seconds() 318 31536000.0 278 319 >>> year == another_year 279 320 True … … 317 358 If an argument outside those ranges is given, :exc:`ValueError` is raised. 318 359 360 319 361 Other constructors, all class methods: 320 362 321 322 .. method:: date.today() 363 .. classmethod:: date.today() 323 364 324 365 Return the current local date. This is equivalent to … … 326 367 327 368 328 .. method:: date.fromtimestamp(timestamp)369 .. classmethod:: date.fromtimestamp(timestamp) 329 370 330 371 Return the local date corresponding to the POSIX timestamp, such as is returned 331 372 by :func:`time.time`. This may raise :exc:`ValueError`, if the timestamp is out 332 of the range of values supported by the platform C :c func:`localtime` function.373 of the range of values supported by the platform C :c:func:`localtime` function. 333 374 It's common for this to be restricted to years from 1970 through 2038. Note 334 375 that on non-POSIX systems that include leap seconds in their notion of a … … 336 377 337 378 338 .. method:: date.fromordinal(ordinal)379 .. classmethod:: date.fromordinal(ordinal) 339 380 340 381 Return the date corresponding to the proleptic Gregorian ordinal, where January … … 343 384 d``. 344 385 386 345 387 Class attributes: 346 347 388 348 389 .. attribute:: date.min … … 361 402 ``timedelta(days=1)``. 362 403 404 363 405 Instance attributes (read-only): 364 406 365 366 407 .. attribute:: date.year 367 408 … … 377 418 378 419 Between 1 and the number of days in the given month of the given year. 420 379 421 380 422 Supported operations: … … 430 472 Instance methods: 431 473 432 433 474 .. method:: date.replace(year, month, day) 434 475 435 Return a date with the same value, except for those members given new values by436 whichever keyword arguments are specified. For example, if ``d == date(2002,437 12, 31)``, then ``d.replace(day=26) == date(2002, 12, 26)``.476 Return a date with the same value, except for those parameters given new 477 values by whichever keyword arguments are specified. For example, if ``d == 478 date(2002, 12, 31)``, then ``d.replace(day=26) == date(2002, 12, 26)``. 438 479 439 480 … … 443 484 The hours, minutes and seconds are 0, and the DST flag is -1. ``d.timetuple()`` 444 485 is equivalent to ``time.struct_time((d.year, d.month, d.day, 0, 0, 0, 445 d.weekday(), d.toordinal() - date(d.year, 1, 1).toordinal() + 1, -1))`` 486 d.weekday(), yday, -1))``, where ``yday = d.toordinal() - date(d.year, 1, 487 1).toordinal() + 1`` is the day number within the current year starting with 488 ``1`` for January 1st. 446 489 447 490 … … 502 545 4).ctime() == 'Wed Dec 4 00:00:00 2002'``. ``d.ctime()`` is equivalent to 503 546 ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the native C 504 :c func:`ctime` function (which :func:`time.ctime` invokes, but which547 :c:func:`ctime` function (which :func:`time.ctime` invokes, but which 505 548 :meth:`date.ctime` does not invoke) conforms to the C standard. 506 549 … … 509 552 510 553 Return a string representing the date, controlled by an explicit format string. 511 Format codes referring to hours, minutes or seconds will see 0 values. See 512 section :ref:`strftime-behavior`. 554 Format codes referring to hours, minutes or seconds will see 0 values. For a 555 complete list of formatting directives, see section 556 :ref:`strftime-strptime-behavior`. 557 558 559 .. method:: date.__format__(format) 560 561 Same as :meth:`.date.strftime`. This makes it possible to specify format 562 string for a :class:`.date` object when using :meth:`str.format`. 563 See section :ref:`strftime-strptime-behavior`. 564 513 565 514 566 Example of counting days to an event:: … … 562 614 >>> d.strftime("%A %d. %B %Y") 563 615 'Monday 11. March 2002' 616 >>> 'The {1} is {0:%d}, the {2} is {0:%B}.'.format(d, "day", "month") 617 'The day is 11, the month is March.' 564 618 565 619 … … 569 623 ------------------------- 570 624 571 A :class:` datetime` object is a single object containing all the information572 from a :class:`date` object and a :class:` time` object. Like a :class:`date`573 object, :class:` datetime` assumes the current Gregorian calendar extended in574 both directions; like a time object, :class:` datetime` assumes there are exactly625 A :class:`.datetime` object is a single object containing all the information 626 from a :class:`date` object and a :class:`.time` object. Like a :class:`date` 627 object, :class:`.datetime` assumes the current Gregorian calendar extended in 628 both directions; like a time object, :class:`.datetime` assumes there are exactly 575 629 3600\*24 seconds in every day. 576 630 577 631 Constructor: 578 579 632 580 633 .. class:: datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]) … … 596 649 Other constructors, all class methods: 597 650 598 599 .. method:: datetime.today() 651 .. classmethod:: datetime.today() 600 652 601 653 Return the current local datetime, with :attr:`tzinfo` ``None``. This is … … 604 656 605 657 606 .. method:: datetime.now([tz])658 .. classmethod:: datetime.now([tz]) 607 659 608 660 Return the current local date and time. If optional argument *tz* is ``None`` … … 610 662 precision than can be gotten from going through a :func:`time.time` timestamp 611 663 (for example, this may be possible on platforms supplying the C 612 :c func:`gettimeofday` function).664 :c:func:`gettimeofday` function). 613 665 614 666 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the … … 618 670 619 671 620 .. method:: datetime.utcnow()672 .. classmethod:: datetime.utcnow() 621 673 622 674 Return the current UTC date and time, with :attr:`tzinfo` ``None``. This is like 623 675 :meth:`now`, but returns the current UTC date and time, as a naive 624 :class:` datetime` object. See also :meth:`now`.625 626 627 .. method:: datetime.fromtimestamp(timestamp[, tz])676 :class:`.datetime` object. See also :meth:`now`. 677 678 679 .. classmethod:: datetime.fromtimestamp(timestamp[, tz]) 628 680 629 681 Return the local date and time corresponding to the POSIX timestamp, such as is 630 682 returned by :func:`time.time`. If optional argument *tz* is ``None`` or not 631 683 specified, the timestamp is converted to the platform's local date and time, and 632 the returned :class:` datetime` object is naive.684 the returned :class:`.datetime` object is naive. 633 685 634 686 Else *tz* must be an instance of a class :class:`tzinfo` subclass, and the … … 638 690 639 691 :meth:`fromtimestamp` may raise :exc:`ValueError`, if the timestamp is out of 640 the range of values supported by the platform C :c func:`localtime` or641 :c func:`gmtime` functions. It's common for this to be restricted to years in692 the range of values supported by the platform C :c:func:`localtime` or 693 :c:func:`gmtime` functions. It's common for this to be restricted to years in 642 694 1970 through 2038. Note that on non-POSIX systems that include leap seconds in 643 695 their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`, 644 696 and then it's possible to have two timestamps differing by a second that yield 645 identical :class:` datetime` objects. See also :meth:`utcfromtimestamp`.646 647 648 .. method:: datetime.utcfromtimestamp(timestamp)649 650 Return the UTC :class:` datetime` corresponding to the POSIX timestamp, with697 identical :class:`.datetime` objects. See also :meth:`utcfromtimestamp`. 698 699 700 .. classmethod:: datetime.utcfromtimestamp(timestamp) 701 702 Return the UTC :class:`.datetime` corresponding to the POSIX timestamp, with 651 703 :attr:`tzinfo` ``None``. This may raise :exc:`ValueError`, if the timestamp is 652 out of the range of values supported by the platform C :c func:`gmtime` function.704 out of the range of values supported by the platform C :c:func:`gmtime` function. 653 705 It's common for this to be restricted to years in 1970 through 2038. See also 654 706 :meth:`fromtimestamp`. 655 707 656 708 657 .. method:: datetime.fromordinal(ordinal)658 659 Return the :class:` datetime` corresponding to the proleptic Gregorian ordinal,709 .. classmethod:: datetime.fromordinal(ordinal) 710 711 Return the :class:`.datetime` corresponding to the proleptic Gregorian ordinal, 660 712 where January 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1 661 713 <= ordinal <= datetime.max.toordinal()``. The hour, minute, second and … … 663 715 664 716 665 .. method:: datetime.combine(date, time) 666 667 Return a new :class:`datetime` object whose date members are equal to the given 668 :class:`date` object's, and whose time and :attr:`tzinfo` members are equal to 669 the given :class:`time` object's. For any :class:`datetime` object *d*, ``d == 670 datetime.combine(d.date(), d.timetz())``. If date is a :class:`datetime` 671 object, its time and :attr:`tzinfo` members are ignored. 672 673 674 .. method:: datetime.strptime(date_string, format) 675 676 Return a :class:`datetime` corresponding to *date_string*, parsed according to 717 .. classmethod:: datetime.combine(date, time) 718 719 Return a new :class:`.datetime` object whose date components are equal to the 720 given :class:`date` object's, and whose time components and :attr:`tzinfo` 721 attributes are equal to the given :class:`.time` object's. For any 722 :class:`.datetime` object *d*, 723 ``d == datetime.combine(d.date(), d.timetz())``. If date is a 724 :class:`.datetime` object, its time components and :attr:`tzinfo` attributes 725 are ignored. 726 727 728 .. classmethod:: datetime.strptime(date_string, format) 729 730 Return a :class:`.datetime` corresponding to *date_string*, parsed according to 677 731 *format*. This is equivalent to ``datetime(*(time.strptime(date_string, 678 732 format)[0:6]))``. :exc:`ValueError` is raised if the date_string and format 679 733 can't be parsed by :func:`time.strptime` or if it returns a value which isn't a 680 time tuple. 734 time tuple. For a complete list of formatting directives, see section 735 :ref:`strftime-strptime-behavior`. 681 736 682 737 .. versionadded:: 2.5 683 738 739 684 740 Class attributes: 685 741 686 687 742 .. attribute:: datetime.min 688 743 689 The earliest representable :class:` datetime`, ``datetime(MINYEAR, 1, 1,744 The earliest representable :class:`.datetime`, ``datetime(MINYEAR, 1, 1, 690 745 tzinfo=None)``. 691 746 … … 693 748 .. attribute:: datetime.max 694 749 695 The latest representable :class:` datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59,750 The latest representable :class:`.datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59, 696 751 59, 999999, tzinfo=None)``. 697 752 … … 699 754 .. attribute:: datetime.resolution 700 755 701 The smallest possible difference between non-equal :class:` datetime` objects,756 The smallest possible difference between non-equal :class:`.datetime` objects, 702 757 ``timedelta(microseconds=1)``. 703 758 759 704 760 Instance attributes (read-only): 705 761 706 707 762 .. attribute:: datetime.year 708 763 … … 742 797 .. attribute:: datetime.tzinfo 743 798 744 The object passed as the *tzinfo* argument to the :class:` datetime` constructor,799 The object passed as the *tzinfo* argument to the :class:`.datetime` constructor, 745 800 or ``None`` if none was passed. 746 801 802 747 803 Supported operations: 748 804 749 +---------------------------------------+------------------------------- +750 | Operation | Result |751 +=======================================+=============================== +752 | ``datetime2 = datetime1 + timedelta`` | \(1) |753 +---------------------------------------+------------------------------- +754 | ``datetime2 = datetime1 - timedelta`` | \(2) |755 +---------------------------------------+------------------------------- +756 | ``timedelta = datetime1 - datetime2`` | \(3) |757 +---------------------------------------+------------------------------- +758 | ``datetime1 < datetime2`` | Compares :class:` datetime` to |759 | | :class:` datetime`. (4) |760 +---------------------------------------+------------------------------- +805 +---------------------------------------+--------------------------------+ 806 | Operation | Result | 807 +=======================================+================================+ 808 | ``datetime2 = datetime1 + timedelta`` | \(1) | 809 +---------------------------------------+--------------------------------+ 810 | ``datetime2 = datetime1 - timedelta`` | \(2) | 811 +---------------------------------------+--------------------------------+ 812 | ``timedelta = datetime1 - datetime2`` | \(3) | 813 +---------------------------------------+--------------------------------+ 814 | ``datetime1 < datetime2`` | Compares :class:`.datetime` to | 815 | | :class:`.datetime`. (4) | 816 +---------------------------------------+--------------------------------+ 761 817 762 818 (1) 763 819 datetime2 is a duration of timedelta removed from datetime1, moving forward in 764 820 time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0. The 765 result has the same :attr:`tzinfo` member as the input datetime, and datetime2 - 766 datetime1 == timedelta after. :exc:`OverflowError` is raised if datetime2.year 767 would be smaller than :const:`MINYEAR` or larger than :const:`MAXYEAR`. Note 768 that no time zone adjustments are done even if the input is an aware object. 821 result has the same :attr:`tzinfo` attribute as the input datetime, and 822 datetime2 - datetime1 == timedelta after. :exc:`OverflowError` is raised if 823 datetime2.year would be smaller than :const:`MINYEAR` or larger than 824 :const:`MAXYEAR`. Note that no time zone adjustments are done even if the 825 input is an aware object. 769 826 770 827 (2) 771 828 Computes the datetime2 such that datetime2 + timedelta == datetime1. As for 772 addition, the result has the same :attr:`tzinfo` member as the input datetime,773 and no time zone adjustments are done even if the input is aware. This isn't774 quite equivalent to datetime1 + (-timedelta), because -timedelta in isolation775 can overflow in cases where datetime1 - timedelta does not.829 addition, the result has the same :attr:`tzinfo` attribute as the input 830 datetime, and no time zone adjustments are done even if the input is aware. 831 This isn't quite equivalent to datetime1 + (-timedelta), because -timedelta 832 in isolation can overflow in cases where datetime1 - timedelta does not. 776 833 777 834 (3) 778 Subtraction of a :class:` datetime` from a :class:`datetime` is defined only if835 Subtraction of a :class:`.datetime` from a :class:`.datetime` is defined only if 779 836 both operands are naive, or if both are aware. If one is aware and the other is 780 837 naive, :exc:`TypeError` is raised. 781 838 782 If both are naive, or both are aware and have the same :attr:`tzinfo` member,783 the :attr:`tzinfo` members are ignored, and the result is a :class:`timedelta`839 If both are naive, or both are aware and have the same :attr:`tzinfo` attribute, 840 the :attr:`tzinfo` attributes are ignored, and the result is a :class:`timedelta` 784 841 object *t* such that ``datetime2 + t == datetime1``. No time zone adjustments 785 842 are done in this case. 786 843 787 If both are aware and have different :attr:`tzinfo` members, ``a-b`` acts as if788 *a* and *b* were first converted to naive UTC datetimes first. The result is789 ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None) -790 b.utcoffset())`` except that the implementation never overflows.844 If both are aware and have different :attr:`tzinfo` attributes, ``a-b`` acts 845 as if *a* and *b* were first converted to naive UTC datetimes first. The 846 result is ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None) 847 - b.utcoffset())`` except that the implementation never overflows. 791 848 792 849 (4) … … 795 852 796 853 If one comparand is naive and the other is aware, :exc:`TypeError` is raised. 797 If both comparands are aware, and have the same :attr:`tzinfo` member, the798 common :attr:`tzinfo` member is ignored and the base datetimes are compared. If799 both comparands are aware and have different :attr:`tzinfo` members, the800 comparands are first adjusted by subtracting their UTC offsets (obtained from801 ``self.utcoffset()``).854 If both comparands are aware, and have the same :attr:`tzinfo` attribute, the 855 common :attr:`tzinfo` attribute is ignored and the base datetimes are 856 compared. If both comparands are aware and have different :attr:`tzinfo` 857 attributes, the comparands are first adjusted by subtracting their UTC 858 offsets (obtained from ``self.utcoffset()``). 802 859 803 860 .. note:: … … 805 862 In order to stop comparison from falling back to the default scheme of comparing 806 863 object addresses, datetime comparison normally raises :exc:`TypeError` if the 807 other comparand isn't also a :class:` datetime` object. However,864 other comparand isn't also a :class:`.datetime` object. However, 808 865 ``NotImplemented`` is returned instead if the other comparand has a 809 866 :meth:`timetuple` attribute. This hook gives other kinds of date objects a 810 chance at implementing mixed-type comparison. If not, when a :class:` datetime`867 chance at implementing mixed-type comparison. If not, when a :class:`.datetime` 811 868 object is compared to an object of a different type, :exc:`TypeError` is raised 812 869 unless the comparison is ``==`` or ``!=``. The latter cases return 813 870 :const:`False` or :const:`True`, respectively. 814 871 815 :class:` datetime` objects can be used as dictionary keys. In Boolean contexts,816 all :class:` datetime` objects are considered to be true.872 :class:`.datetime` objects can be used as dictionary keys. In Boolean contexts, 873 all :class:`.datetime` objects are considered to be true. 817 874 818 875 Instance methods: 819 876 820 821 877 .. method:: datetime.date() 822 878 … … 826 882 .. method:: datetime.time() 827 883 828 Return :class:` time` object with same hour, minute, second and microsecond.884 Return :class:`.time` object with same hour, minute, second and microsecond. 829 885 :attr:`tzinfo` is ``None``. See also method :meth:`timetz`. 830 886 … … 832 888 .. method:: datetime.timetz() 833 889 834 Return :class:` time` object with same hour, minute, second, microsecond, and835 tzinfo members. See also method :meth:`time`.890 Return :class:`.time` object with same hour, minute, second, microsecond, and 891 tzinfo attributes. See also method :meth:`time`. 836 892 837 893 838 894 .. method:: datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]]) 839 895 840 Return a datetime with the same members, except for those members given new841 values by whichever keyword arguments are specified. Note that ``tzinfo=None``842 can be specified to create a naive datetime from an aware datetime with no843 conversion of date and time members.896 Return a datetime with the same attributes, except for those attributes given 897 new values by whichever keyword arguments are specified. Note that 898 ``tzinfo=None`` can be specified to create a naive datetime from an aware 899 datetime with no conversion of date and time data. 844 900 845 901 846 902 .. method:: datetime.astimezone(tz) 847 903 848 Return a :class:` datetime` object with new :attr:`tzinfo` member *tz*, adjusting849 the date and time members so the result is the same UTC time as *self*, but in850 * tz*'s local time.904 Return a :class:`.datetime` object with new :attr:`tzinfo` attribute *tz*, 905 adjusting the date and time data so the result is the same UTC time as 906 *self*, but in *tz*'s local time. 851 907 852 908 *tz* must be an instance of a :class:`tzinfo` subclass, and its … … 856 912 857 913 If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*: no 858 adjustment of date or time members is performed. Else the result is local time859 in time zone *tz*, representing the same UTC time as *self*: after ``astz =860 dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will usually have the same date861 and time members as ``dt - dt.utcoffset()``. The discussion of class862 :class:`tzinfo` explains the cases at Daylight Saving Time transition boundaries863 where this cannot be achieved (an issue only if *tz* models both standard and864 daylight time).914 adjustment of date or time data is performed. Else the result is local 915 time in time zone *tz*, representing the same UTC time as *self*: after 916 ``astz = dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will usually have 917 the same date and time data as ``dt - dt.utcoffset()``. The discussion 918 of class :class:`tzinfo` explains the cases at Daylight Saving Time transition 919 boundaries where this cannot be achieved (an issue only if *tz* models both 920 standard and daylight time). 865 921 866 922 If you merely want to attach a time zone object *tz* to a datetime *dt* without 867 adjustment of date and time members, use ``dt.replace(tzinfo=tz)``. If you923 adjustment of date and time data, use ``dt.replace(tzinfo=tz)``. If you 868 924 merely want to remove the time zone object from an aware datetime *dt* without 869 conversion of date and time members, use ``dt.replace(tzinfo=None)``.925 conversion of date and time data, use ``dt.replace(tzinfo=None)``. 870 926 871 927 Note that the default :meth:`tzinfo.fromutc` method can be overridden in a … … 909 965 Return a :class:`time.struct_time` such as returned by :func:`time.localtime`. 910 966 ``d.timetuple()`` is equivalent to ``time.struct_time((d.year, d.month, d.day, 911 d.hour, d.minute, d.second, d.weekday(), d.toordinal() - date(d.year, 1, 912 1).toordinal() + 1, dst))`` The :attr:`tm_isdst` flag of the result is set 913 according to the :meth:`dst` method: :attr:`tzinfo` is ``None`` or :meth:`dst` 914 returns ``None``, :attr:`tm_isdst` is set to ``-1``; else if :meth:`dst` 915 returns a non-zero value, :attr:`tm_isdst` is set to ``1``; else ``tm_isdst`` is 916 set to ``0``. 967 d.hour, d.minute, d.second, d.weekday(), yday, dst))``, where ``yday = 968 d.toordinal() - date(d.year, 1, 1).toordinal() + 1`` is the day number within 969 the current year starting with ``1`` for January 1st. The :attr:`tm_isdst` flag 970 of the result is set according to the :meth:`dst` method: :attr:`tzinfo` is 971 ``None`` or :meth:`dst` returns ``None``, :attr:`tm_isdst` is set to ``-1``; 972 else if :meth:`dst` returns a non-zero value, :attr:`tm_isdst` is set to ``1``; 973 else :attr:`tm_isdst` is set to ``0``. 917 974 918 975 919 976 .. method:: datetime.utctimetuple() 920 977 921 If :class:` datetime` instance *d* is naive, this is the same as978 If :class:`.datetime` instance *d* is naive, this is the same as 922 979 ``d.timetuple()`` except that :attr:`tm_isdst` is forced to 0 regardless of what 923 980 ``d.dst()`` returns. DST is never in effect for a UTC time. … … 980 1037 .. method:: datetime.__str__() 981 1038 982 For a :class:` datetime` instance *d*, ``str(d)`` is equivalent to1039 For a :class:`.datetime` instance *d*, ``str(d)`` is equivalent to 983 1040 ``d.isoformat(' ')``. 984 1041 … … 989 1046 4, 20, 30, 40).ctime() == 'Wed Dec 4 20:30:40 2002'``. ``d.ctime()`` is 990 1047 equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the 991 native C :c func:`ctime` function (which :func:`time.ctime` invokes, but which1048 native C :c:func:`ctime` function (which :func:`time.ctime` invokes, but which 992 1049 :meth:`datetime.ctime` does not invoke) conforms to the C standard. 993 1050 … … 996 1053 997 1054 Return a string representing the date and time, controlled by an explicit format 998 string. See section :ref:`strftime-behavior`. 1055 string. For a complete list of formatting directives, see section 1056 :ref:`strftime-strptime-behavior`. 1057 1058 1059 .. method:: datetime.__format__(format) 1060 1061 Same as :meth:`.datetime.strftime`. This makes it possible to specify format 1062 string for a :class:`.datetime` object when using :meth:`str.format`. 1063 See section :ref:`strftime-strptime-behavior`. 1064 999 1065 1000 1066 Examples of working with datetime objects: … … 1042 1108 >>> dt.strftime("%A, %d. %B %Y %I:%M%p") 1043 1109 'Tuesday, 21. November 2006 04:30PM' 1110 >>> 'The {1} is {0:%d}, the {2} is {0:%B}, the {3} is {0:%I:%M%p}.'.format(dt, "day", "month", "time") 1111 'The day is 21, the month is November, the time is 04:30PM.' 1044 1112 1045 1113 Using datetime with tzinfo: … … 1047 1115 >>> from datetime import timedelta, datetime, tzinfo 1048 1116 >>> class GMT1(tzinfo): 1049 ... def __init__(self): # DST starts last Sunday in March 1117 ... def utcoffset(self, dt): 1118 ... return timedelta(hours=1) + self.dst(dt) 1119 ... def dst(self, dt): 1120 ... # DST starts last Sunday in March 1050 1121 ... d = datetime(dt.year, 4, 1) # ends last Sunday in October 1051 1122 ... self.dston = d - timedelta(days=d.weekday() + 1) 1052 1123 ... d = datetime(dt.year, 11, 1) 1053 1124 ... self.dstoff = d - timedelta(days=d.weekday() + 1) 1054 ... def utcoffset(self, dt):1055 ... return timedelta(hours=1) + self.dst(dt)1056 ... def dst(self, dt):1057 1125 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff: 1058 1126 ... return timedelta(hours=1) … … 1063 1131 ... 1064 1132 >>> class GMT2(tzinfo): 1065 ... def __init__(self): 1133 ... def utcoffset(self, dt): 1134 ... return timedelta(hours=2) + self.dst(dt) 1135 ... def dst(self, dt): 1066 1136 ... d = datetime(dt.year, 4, 1) 1067 1137 ... self.dston = d - timedelta(days=d.weekday() + 1) 1068 1138 ... d = datetime(dt.year, 11, 1) 1069 1139 ... self.dstoff = d - timedelta(days=d.weekday() + 1) 1070 ... def utcoffset(self, dt):1071 ... return timedelta(hours=1) + self.dst(dt)1072 ... def dst(self, dt):1073 1140 ... if self.dston <= dt.replace(tzinfo=None) < self.dstoff: 1074 ... return timedelta(hours= 2)1141 ... return timedelta(hours=1) 1075 1142 ... else: 1076 1143 ... return timedelta(0) … … 1109 1176 day, and subject to adjustment via a :class:`tzinfo` object. 1110 1177 1111 1112 .. class:: time(hour[, minute[, second[, microsecond[, tzinfo]]]]) 1178 .. class:: time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) 1113 1179 1114 1180 All arguments are optional. *tzinfo* may be ``None``, or an instance of a … … 1129 1195 .. attribute:: time.min 1130 1196 1131 The earliest representable :class:` time`, ``time(0, 0, 0, 0)``.1197 The earliest representable :class:`.time`, ``time(0, 0, 0, 0)``. 1132 1198 1133 1199 1134 1200 .. attribute:: time.max 1135 1201 1136 The latest representable :class:` time`, ``time(23, 59, 59, 999999)``.1202 The latest representable :class:`.time`, ``time(23, 59, 59, 999999)``. 1137 1203 1138 1204 1139 1205 .. attribute:: time.resolution 1140 1206 1141 The smallest possible difference between non-equal :class:`time` objects, 1142 ``timedelta(microseconds=1)``, although note that arithmetic on :class:`time` 1143 objects is not supported. 1207 The smallest possible difference between non-equal :class:`.time` objects, 1208 ``timedelta(microseconds=1)``, although note that arithmetic on 1209 :class:`.time` objects is not supported. 1210 1144 1211 1145 1212 Instance attributes (read-only): 1146 1213 1147 1148 1214 .. attribute:: time.hour 1149 1215 … … 1168 1234 .. attribute:: time.tzinfo 1169 1235 1170 The object passed as the tzinfo argument to the :class:` time` constructor, or1236 The object passed as the tzinfo argument to the :class:`.time` constructor, or 1171 1237 ``None`` if none was passed. 1172 1238 1239 1173 1240 Supported operations: 1174 1241 1175 * comparison of :class:` time` to :class:`time`, where *a* is considered less1242 * comparison of :class:`.time` to :class:`.time`, where *a* is considered less 1176 1243 than *b* when *a* precedes *b* in time. If one comparand is naive and the other 1177 1244 is aware, :exc:`TypeError` is raised. If both comparands are aware, and have 1178 the same :attr:`tzinfo` member, the common :attr:`tzinfo` member is ignored and1179 the base times are compared. If both comparands are aware and have different1180 :attr:`tzinfo` members, the comparands are first adjusted by subtracting their1181 UTC offsets (obtained from ``self.utcoffset()``). In order to stop mixed-type1182 comparisons from falling back to the default comparison by object address, when1183 a :class:`time` object is compared to an object of a different type,1184 :exc:`TypeError` is raised unless the comparison is ``==`` or ``!=``. The1185 latter cases return :const:`False` or :const:`True`, respectively.1245 the same :attr:`tzinfo` attribute, the common :attr:`tzinfo` attribute is 1246 ignored and the base times are compared. If both comparands are aware and 1247 have different :attr:`tzinfo` attributes, the comparands are first adjusted by 1248 subtracting their UTC offsets (obtained from ``self.utcoffset()``). In order 1249 to stop mixed-type comparisons from falling back to the default comparison by 1250 object address, when a :class:`.time` object is compared to an object of a 1251 different type, :exc:`TypeError` is raised unless the comparison is ``==`` or 1252 ``!=``. The latter cases return :const:`False` or :const:`True`, respectively. 1186 1253 1187 1254 * hash, use as dict key … … 1189 1256 * efficient pickling 1190 1257 1191 * in Boolean contexts, a :class:` time` object is considered to be true if and1258 * in Boolean contexts, a :class:`.time` object is considered to be true if and 1192 1259 only if, after converting it to minutes and subtracting :meth:`utcoffset` (or 1193 1260 ``0`` if that's ``None``), the result is non-zero. 1194 1261 1262 1195 1263 Instance methods: 1196 1264 1197 1198 1265 .. method:: time.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]]) 1199 1266 1200 Return a :class:` time` with the same value, except for those members given new1201 values by whichever keyword arguments are specified. Note that ``tzinfo=None``1202 can be specified to create a naive :class:`time` from an aware :class:`time`,1203 without conversion of the time members.1267 Return a :class:`.time` with the same value, except for those attributes given 1268 new values by whichever keyword arguments are specified. Note that 1269 ``tzinfo=None`` can be specified to create a naive :class:`.time` from an 1270 aware :class:`.time`, without conversion of the time data. 1204 1271 1205 1272 … … 1220 1287 1221 1288 Return a string representing the time, controlled by an explicit format string. 1222 See section :ref:`strftime-behavior`. 1289 For a complete list of formatting directives, see section 1290 :ref:`strftime-strptime-behavior`. 1291 1292 1293 .. method:: time.__format__(format) 1294 1295 Same as :meth:`.time.strftime`. This makes it possible to specify format string 1296 for a :class:`.time` object when using :meth:`str.format`. 1297 See section :ref:`strftime-strptime-behavior`. 1223 1298 1224 1299 … … 1244 1319 ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't 1245 1320 return ``None`` or a string object. 1321 1246 1322 1247 1323 Example: … … 1268 1344 >>> t.strftime("%H:%M:%S %Z") 1269 1345 '12:10:30 Europe/Prague' 1346 >>> 'The {} is {:%H:%M}.'.format("time", t) 1347 'The time is 12:10.' 1270 1348 1271 1349 … … 1278 1356 instantiated directly. You need to derive a concrete subclass, and (at least) 1279 1357 supply implementations of the standard :class:`tzinfo` methods needed by the 1280 :class:` datetime` methods you use. The :mod:`datetime` module does not supply1358 :class:`.datetime` methods you use. The :mod:`datetime` module does not supply 1281 1359 any concrete subclasses of :class:`tzinfo`. 1282 1360 1283 1361 An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the 1284 constructors for :class:` datetime` and :class:`time` objects. The latter objects1285 view their members as being in local time, and the :class:`tzinfo` object1362 constructors for :class:`.datetime` and :class:`.time` objects. The latter objects 1363 view their attributes as being in local time, and the :class:`tzinfo` object 1286 1364 supports methods revealing offset of local time from UTC, the name of the time 1287 1365 zone, and DST offset, all relative to a date or time object passed to them. … … 1328 1406 no need to consult :meth:`dst` unless you're interested in obtaining DST info 1329 1407 separately. For example, :meth:`datetime.timetuple` calls its :attr:`tzinfo` 1330 member's :meth:`dst` method to determine how the :attr:`tm_isdst` flag should be1331 s et, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for DST changes1332 when crossing time zones.1408 attribute's :meth:`dst` method to determine how the :attr:`tm_isdst` flag 1409 should be set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for 1410 DST changes when crossing time zones. 1333 1411 1334 1412 An instance *tz* of a :class:`tzinfo` subclass that models both standard and … … 1337 1415 ``tz.utcoffset(dt) - tz.dst(dt)`` 1338 1416 1339 must return the same result for every :class:` datetime` *dt* with ``dt.tzinfo ==1417 must return the same result for every :class:`.datetime` *dt* with ``dt.tzinfo == 1340 1418 tz`` For sane :class:`tzinfo` subclasses, this expression yields the time 1341 1419 zone's "standard offset", which should not depend on the date or the time, but … … 1348 1426 Most implementations of :meth:`dst` will probably look like one of these two:: 1349 1427 1350 def dst(self ):1428 def dst(self, dt): 1351 1429 # a fixed-offset class: doesn't account for DST 1352 1430 return timedelta(0) … … 1354 1432 or :: 1355 1433 1356 def dst(self ):1434 def dst(self, dt): 1357 1435 # Code to set dston and dstoff to the time zone's DST 1358 1436 # transition times based on the input dt.year, and expressed … … 1369 1447 .. method:: tzinfo.tzname(self, dt) 1370 1448 1371 Return the time zone name corresponding to the :class:` datetime` object *dt*, as1449 Return the time zone name corresponding to the :class:`.datetime` object *dt*, as 1372 1450 a string. Nothing about string names is defined by the :mod:`datetime` module, 1373 1451 and there's no requirement that it mean anything in particular. For example, … … 1381 1459 The default implementation of :meth:`tzname` raises :exc:`NotImplementedError`. 1382 1460 1383 These methods are called by a :class:`datetime` or :class:`time` object, in 1384 response to their methods of the same names. A :class:`datetime` object passes 1385 itself as the argument, and a :class:`time` object passes ``None`` as the 1461 1462 These methods are called by a :class:`.datetime` or :class:`.time` object, in 1463 response to their methods of the same names. A :class:`.datetime` object passes 1464 itself as the argument, and a :class:`.time` object passes ``None`` as the 1386 1465 argument. A :class:`tzinfo` subclass's methods should therefore be prepared to 1387 accept a *dt* argument of ``None``, or of class :class:` datetime`.1466 accept a *dt* argument of ``None``, or of class :class:`.datetime`. 1388 1467 1389 1468 When ``None`` is passed, it's up to the class designer to decide the best … … 1393 1472 there is no other convention for discovering the standard offset. 1394 1473 1395 When a :class:` datetime` object is passed in response to a :class:`datetime`1474 When a :class:`.datetime` object is passed in response to a :class:`.datetime` 1396 1475 method, ``dt.tzinfo`` is the same object as *self*. :class:`tzinfo` methods can 1397 1476 rely on this, unless user code calls :class:`tzinfo` methods directly. The … … 1404 1483 .. method:: tzinfo.fromutc(self, dt) 1405 1484 1406 This is called from the default :class:`datetime.astimezone()` implementation.1407 When called from that, ``dt.tzinfo`` is *self*, and *dt*'s date and time members1408 are to be viewed as expressing a UTC time. The purpose of :meth:`fromutc` is to1409 adjust the date and time members, returning an equivalent datetime in *self*'s1410 local time.1485 This is called from the default :class:`datetime.astimezone()` 1486 implementation. When called from that, ``dt.tzinfo`` is *self*, and *dt*'s 1487 date and time data are to be viewed as expressing a UTC time. The purpose 1488 of :meth:`fromutc` is to adjust the date and time data, returning an 1489 equivalent datetime in *self*'s local time. 1411 1490 1412 1491 Most :class:`tzinfo` subclasses should be able to inherit the default … … 1447 1526 subclass accounting for both standard and daylight time, at the DST transition 1448 1527 points. For concreteness, consider US Eastern (UTC -0500), where EDT begins the 1449 minute after 1:59 (EST) on the first Sunday in April, and ends the minute after1450 1:59 (EDT) on the last Sunday in October::1528 minute after 1:59 (EST) on the second Sunday in March, and ends the minute after 1529 1:59 (EDT) on the first Sunday in November:: 1451 1530 1452 1531 UTC 3:MM 4:MM 5:MM 6:MM 7:MM 8:MM … … 1483 1562 EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)). 1484 1563 1485 1486 .. _strftime-behavior: 1487 1488 :meth:`strftime` Behavior 1489 ------------------------- 1490 1491 :class:`date`, :class:`datetime`, and :class:`time` objects all support a 1564 .. seealso:: 1565 1566 `pytz <http://pypi.python.org/pypi/pytz/>`_ 1567 The standard library has no :class:`tzinfo` instances, but 1568 there exists a third-party library which brings the *IANA timezone 1569 database* (also known as the Olson database) to Python: *pytz*. 1570 1571 *pytz* contains up-to-date information and its usage is recommended. 1572 1573 `IANA timezone database <http://www.iana.org/time-zones>`_ 1574 The Time Zone Database (often called tz or zoneinfo) contains code and 1575 data that represent the history of local time for many representative 1576 locations around the globe. It is updated periodically to reflect changes 1577 made by political bodies to time zone boundaries, UTC offsets, and 1578 daylight-saving rules. 1579 1580 .. _strftime-strptime-behavior: 1581 1582 :meth:`strftime` and :meth:`strptime` Behavior 1583 ---------------------------------------------- 1584 1585 :class:`date`, :class:`.datetime`, and :class:`.time` objects all support a 1492 1586 ``strftime(format)`` method, to create a string representing the time under the 1493 1587 control of an explicit format string. Broadly speaking, ``d.strftime(fmt)`` … … 1495 1589 although not all objects support a :meth:`timetuple` method. 1496 1590 1497 For :class:`time` objects, the format codes for year, month, and day should not 1591 Conversely, the :meth:`datetime.strptime` class method creates a 1592 :class:`.datetime` object from a string representing a date and time and a 1593 corresponding format string. ``datetime.strptime(date_string, format)`` is 1594 equivalent to ``datetime(*(time.strptime(date_string, format)[0:6]))``. 1595 1596 For :class:`.time` objects, the format codes for year, month, and day should not 1498 1597 be used, as time objects have no such values. If they're used anyway, ``1900`` 1499 is substituted for the year, and `` 0`` for the month and day.1598 is substituted for the year, and ``1`` for the month and day. 1500 1599 1501 1600 For :class:`date` objects, the format codes for hours, minutes, seconds, and … … 1503 1602 values. If they're used anyway, ``0`` is substituted for them. 1504 1603 1505 .. versionadded:: 2.61506 :class:`time` and :class:`datetime` objects support a ``%f`` format code1507 which expands to the number of microseconds in the object, zero-padded on1508 the left to six places.1509 1510 For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty1511 strings.1512 1513 For an aware object:1514 1515 ``%z``1516 :meth:`utcoffset` is transformed into a 5-character string of the form +HHMM or1517 -HHMM, where HH is a 2-digit string giving the number of UTC offset hours, and1518 MM is a 2-digit string giving the number of UTC offset minutes. For example, if1519 :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``, ``%z`` is1520 replaced with the string ``'-0330'``.1521 1522 ``%Z``1523 If :meth:`tzname` returns ``None``, ``%Z`` is replaced by an empty string.1524 Otherwise ``%Z`` is replaced by the returned value, which must be a string.1525 1526 1604 The full set of format codes supported varies across platforms, because Python 1527 1605 calls the platform C library's :func:`strftime` function, and platform 1528 variations are common. 1606 variations are common. To see the full set of format codes supported on your 1607 platform, consult the :manpage:`strftime(3)` documentation. 1529 1608 1530 1609 The following is a list of all the format codes that the C standard (1989 … … 1536 1615 platforms. Regardless of platform, years before 1900 cannot be used. 1537 1616 1538 +-----------+--------------------------------+-------+ 1539 | Directive | Meaning | Notes | 1540 +===========+================================+=======+ 1541 | ``%a`` | Locale's abbreviated weekday | | 1542 | | name. | | 1543 +-----------+--------------------------------+-------+ 1544 | ``%A`` | Locale's full weekday name. | | 1545 +-----------+--------------------------------+-------+ 1546 | ``%b`` | Locale's abbreviated month | | 1547 | | name. | | 1548 +-----------+--------------------------------+-------+ 1549 | ``%B`` | Locale's full month name. | | 1550 +-----------+--------------------------------+-------+ 1551 | ``%c`` | Locale's appropriate date and | | 1552 | | time representation. | | 1553 +-----------+--------------------------------+-------+ 1554 | ``%d`` | Day of the month as a decimal | | 1555 | | number [01,31]. | | 1556 +-----------+--------------------------------+-------+ 1557 | ``%f`` | Microsecond as a decimal | \(1) | 1558 | | number [0,999999], zero-padded | | 1559 | | on the left | | 1560 +-----------+--------------------------------+-------+ 1561 | ``%H`` | Hour (24-hour clock) as a | | 1562 | | decimal number [00,23]. | | 1563 +-----------+--------------------------------+-------+ 1564 | ``%I`` | Hour (12-hour clock) as a | | 1565 | | decimal number [01,12]. | | 1566 +-----------+--------------------------------+-------+ 1567 | ``%j`` | Day of the year as a decimal | | 1568 | | number [001,366]. | | 1569 +-----------+--------------------------------+-------+ 1570 | ``%m`` | Month as a decimal number | | 1571 | | [01,12]. | | 1572 +-----------+--------------------------------+-------+ 1573 | ``%M`` | Minute as a decimal number | | 1574 | | [00,59]. | | 1575 +-----------+--------------------------------+-------+ 1576 | ``%p`` | Locale's equivalent of either | \(2) | 1577 | | AM or PM. | | 1578 +-----------+--------------------------------+-------+ 1579 | ``%S`` | Second as a decimal number | \(3) | 1580 | | [00,61]. | | 1581 +-----------+--------------------------------+-------+ 1582 | ``%U`` | Week number of the year | \(4) | 1583 | | (Sunday as the first day of | | 1584 | | the week) as a decimal number | | 1585 | | [00,53]. All days in a new | | 1586 | | year preceding the first | | 1587 | | Sunday are considered to be in | | 1588 | | week 0. | | 1589 +-----------+--------------------------------+-------+ 1590 | ``%w`` | Weekday as a decimal number | | 1591 | | [0(Sunday),6]. | | 1592 +-----------+--------------------------------+-------+ 1593 | ``%W`` | Week number of the year | \(4) | 1594 | | (Monday as the first day of | | 1595 | | the week) as a decimal number | | 1596 | | [00,53]. All days in a new | | 1597 | | year preceding the first | | 1598 | | Monday are considered to be in | | 1599 | | week 0. | | 1600 +-----------+--------------------------------+-------+ 1601 | ``%x`` | Locale's appropriate date | | 1602 | | representation. | | 1603 +-----------+--------------------------------+-------+ 1604 | ``%X`` | Locale's appropriate time | | 1605 | | representation. | | 1606 +-----------+--------------------------------+-------+ 1607 | ``%y`` | Year without century as a | | 1608 | | decimal number [00,99]. | | 1609 +-----------+--------------------------------+-------+ 1610 | ``%Y`` | Year with century as a decimal | | 1611 | | number. | | 1612 +-----------+--------------------------------+-------+ 1613 | ``%z`` | UTC offset in the form +HHMM | \(5) | 1614 | | or -HHMM (empty string if the | | 1615 | | the object is naive). | | 1616 +-----------+--------------------------------+-------+ 1617 | ``%Z`` | Time zone name (empty string | | 1618 | | if the object is naive). | | 1619 +-----------+--------------------------------+-------+ 1620 | ``%%`` | A literal ``'%'`` character. | | 1621 +-----------+--------------------------------+-------+ 1617 +-----------+--------------------------------+------------------------+-------+ 1618 | Directive | Meaning | Example | Notes | 1619 +===========+================================+========================+=======+ 1620 | ``%a`` | Weekday as locale's || Sun, Mon, ..., Sat | \(1) | 1621 | | abbreviated name. | (en_US); | | 1622 | | || So, Mo, ..., Sa | | 1623 | | | (de_DE) | | 1624 +-----------+--------------------------------+------------------------+-------+ 1625 | ``%A`` | Weekday as locale's full name. || Sunday, Monday, ..., | \(1) | 1626 | | | Saturday (en_US); | | 1627 | | || Sonntag, Montag, ..., | | 1628 | | | Samstag (de_DE) | | 1629 +-----------+--------------------------------+------------------------+-------+ 1630 | ``%w`` | Weekday as a decimal number, | 0, 1, ..., 6 | | 1631 | | where 0 is Sunday and 6 is | | | 1632 | | Saturday. | | | 1633 +-----------+--------------------------------+------------------------+-------+ 1634 | ``%d`` | Day of the month as a | 01, 02, ..., 31 | | 1635 | | zero-padded decimal number. | | | 1636 +-----------+--------------------------------+------------------------+-------+ 1637 | ``%b`` | Month as locale's abbreviated || Jan, Feb, ..., Dec | \(1) | 1638 | | name. | (en_US); | | 1639 | | || Jan, Feb, ..., Dez | | 1640 | | | (de_DE) | | 1641 +-----------+--------------------------------+------------------------+-------+ 1642 | ``%B`` | Month as locale's full name. || January, February, | \(1) | 1643 | | | ..., December (en_US);| | 1644 | | || Januar, Februar, ..., | | 1645 | | | Dezember (de_DE) | | 1646 +-----------+--------------------------------+------------------------+-------+ 1647 | ``%m`` | Month as a zero-padded | 01, 02, ..., 12 | | 1648 | | decimal number. | | | 1649 +-----------+--------------------------------+------------------------+-------+ 1650 | ``%y`` | Year without century as a | 00, 01, ..., 99 | | 1651 | | zero-padded decimal number. | | | 1652 +-----------+--------------------------------+------------------------+-------+ 1653 | ``%Y`` | Year with century as a decimal | 1970, 1988, 2001, 2013 | | 1654 | | number. | | | 1655 +-----------+--------------------------------+------------------------+-------+ 1656 | ``%H`` | Hour (24-hour clock) as a | 00, 01, ..., 23 | | 1657 | | zero-padded decimal number. | | | 1658 +-----------+--------------------------------+------------------------+-------+ 1659 | ``%I`` | Hour (12-hour clock) as a | 01, 02, ..., 12 | | 1660 | | zero-padded decimal number. | | | 1661 +-----------+--------------------------------+------------------------+-------+ 1662 | ``%p`` | Locale's equivalent of either || AM, PM (en_US); | \(1), | 1663 | | AM or PM. || am, pm (de_DE) | \(2) | 1664 +-----------+--------------------------------+------------------------+-------+ 1665 | ``%M`` | Minute as a zero-padded | 00, 01, ..., 59 | | 1666 | | decimal number. | | | 1667 +-----------+--------------------------------+------------------------+-------+ 1668 | ``%S`` | Second as a zero-padded | 00, 01, ..., 59 | \(3) | 1669 | | decimal number. | | | 1670 +-----------+--------------------------------+------------------------+-------+ 1671 | ``%f`` | Microsecond as a decimal | 000000, 000001, ..., | \(4) | 1672 | | number, zero-padded on the | 999999 | | 1673 | | left. | | | 1674 +-----------+--------------------------------+------------------------+-------+ 1675 | ``%z`` | UTC offset in the form +HHMM | (empty), +0000, -0400, | \(5) | 1676 | | or -HHMM (empty string if the | +1030 | | 1677 | | the object is naive). | | | 1678 +-----------+--------------------------------+------------------------+-------+ 1679 | ``%Z`` | Time zone name (empty string | (empty), UTC, EST, CST | | 1680 | | if the object is naive). | | | 1681 +-----------+--------------------------------+------------------------+-------+ 1682 | ``%j`` | Day of the year as a | 001, 002, ..., 366 | | 1683 | | zero-padded decimal number. | | | 1684 +-----------+--------------------------------+------------------------+-------+ 1685 | ``%U`` | Week number of the year | 00, 01, ..., 53 | \(6) | 1686 | | (Sunday as the first day of | | | 1687 | | the week) as a zero padded | | | 1688 | | decimal number. All days in a | | | 1689 | | new year preceding the first | | | 1690 | | Sunday are considered to be in | | | 1691 | | week 0. | | | 1692 +-----------+--------------------------------+------------------------+-------+ 1693 | ``%W`` | Week number of the year | 00, 01, ..., 53 | \(6) | 1694 | | (Monday as the first day of | | | 1695 | | the week) as a decimal number. | | | 1696 | | All days in a new year | | | 1697 | | preceding the first Monday | | | 1698 | | are considered to be in | | | 1699 | | week 0. | | | 1700 +-----------+--------------------------------+------------------------+-------+ 1701 | ``%c`` | Locale's appropriate date and || Tue Aug 16 21:30:00 | \(1) | 1702 | | time representation. | 1988 (en_US); | | 1703 | | || Di 16 Aug 21:30:00 | | 1704 | | | 1988 (de_DE) | | 1705 +-----------+--------------------------------+------------------------+-------+ 1706 | ``%x`` | Locale's appropriate date || 08/16/88 (None); | \(1) | 1707 | | representation. || 08/16/1988 (en_US); | | 1708 | | || 16.08.1988 (de_DE) | | 1709 +-----------+--------------------------------+------------------------+-------+ 1710 | ``%X`` | Locale's appropriate time || 21:30:00 (en_US); | \(1) | 1711 | | representation. || 21:30:00 (de_DE) | | 1712 +-----------+--------------------------------+------------------------+-------+ 1713 | ``%%`` | A literal ``'%'`` character. | % | | 1714 +-----------+--------------------------------+------------------------+-------+ 1622 1715 1623 1716 Notes: 1624 1717 1625 1718 (1) 1626 When used with the :func:`strptime` function, the ``%f`` directive 1627 accepts from one to six digits and zero pads on the right. ``%f`` is 1628 an extension to the set of format characters in the C standard (but 1629 implemented separately in datetime objects, and therefore always 1630 available). 1719 Because the format depends on the current locale, care should be taken when 1720 making assumptions about the output value. Field orderings will vary (for 1721 example, "month/day/year" versus "day/month/year"), and the output may 1722 contain Unicode characters encoded using the locale's default encoding (for 1723 example, if the current locale is ``js_JP``, the default encoding could be 1724 any one of ``eucJP``, ``SJIS``, or ``utf-8``; use :meth:`locale.getlocale` 1725 to determine the current locale's encoding). 1631 1726 1632 1727 (2) 1633 When used with the : func:`strptime` function, the ``%p`` directive only affects1728 When used with the :meth:`strptime` method, the ``%p`` directive only affects 1634 1729 the output hour field if the ``%I`` directive is used to parse the hour. 1635 1730 1636 1731 (3) 1637 The range really is ``0`` to ``61``; according to the Posix standard this 1638 accounts for leap seconds and the (very rare) double leap seconds. 1639 The :mod:`time` module may produce and does accept leap seconds since 1640 it is based on the Posix standard, but the :mod:`datetime` module 1641 does not accept leap seconds in :func:`strptime` input nor will it 1642 produce them in :func:`strftime` output. 1732 Unlike the :mod:`time` module, the :mod:`datetime` module does not support 1733 leap seconds. 1643 1734 1644 1735 (4) 1645 When used with the :func:`strptime` function, ``%U`` and ``%W`` are only used in 1646 calculations when the day of the week and the year are specified. 1736 ``%f`` is an extension to the set of format characters in the C standard 1737 (but implemented separately in datetime objects, and therefore always 1738 available). When used with the :meth:`strptime` method, the ``%f`` 1739 directive accepts from one to six digits and zero pads on the right. 1740 1741 .. versionadded:: 2.6 1647 1742 1648 1743 (5) 1649 For example, if :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``, 1650 ``%z`` is replaced with the string ``'-0330'``. 1744 For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty 1745 strings. 1746 1747 For an aware object: 1748 1749 ``%z`` 1750 :meth:`utcoffset` is transformed into a 5-character string of the form 1751 +HHMM or -HHMM, where HH is a 2-digit string giving the number of UTC 1752 offset hours, and MM is a 2-digit string giving the number of UTC offset 1753 minutes. For example, if :meth:`utcoffset` returns 1754 ``timedelta(hours=-3, minutes=-30)``, ``%z`` is replaced with the string 1755 ``'-0330'``. 1756 1757 ``%Z`` 1758 If :meth:`tzname` returns ``None``, ``%Z`` is replaced by an empty 1759 string. Otherwise ``%Z`` is replaced by the returned value, which must 1760 be a string. 1761 1762 (6) 1763 When used with the :meth:`strptime` method, ``%U`` and ``%W`` are only used 1764 in calculations when the day of the week and the year are specified. 1765 1766 1767 .. rubric:: Footnotes 1768 1769 .. [#] If, that is, we ignore the effects of Relativity
Note:
See TracChangeset
for help on using the changeset viewer.