/usr/lib/python2.7/dist-packages/isodatetime/data.py is in python-cylc 7.6.0-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 | # -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
# (C) British Crown Copyright 2013-2017 Met Office.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------------------------
"""This provides ISO 8601 data model functionality."""
from . import dumpers
from . import timezone
from . import util
class Calendar(object):
"""Store constants for Gregorian calendar date-time calculation."""
SECONDS_IN_MINUTE = 60
MINUTES_IN_HOUR = 60
HOURS_IN_DAY = 24
DAYS_IN_WEEK = 7
DAYS_IN_MONTHS = None # This is set up in the set_* methods.
DAYS_IN_MONTHS_LEAP = None # This is set up in the set_* methods
ROUGH_DAYS_IN_MONTH = 30 # Used for duration conversion, nowhere else.
LEAP_YEAR_FACTOR_TRUTHS = [(4, True), (100, False), (400, True)]
MODE_360 = "360day"
MODE_365 = "365day"
MODE_366 = "366day"
MODE_GREGORIAN = "gregorian"
# {mode: (days_in_months, days_in_months_leap), ...}
MODES = {
MODE_360: (12 * [30], None),
MODE_365: ([31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], None),
MODE_366: ([31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], None),
MODE_GREGORIAN: (
[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
[31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
),
}
WEEK_DAY_START_REFERENCE = {"calendar": (2000, 1, 3),
"ordinal": (2000, 3)}
UNIX_EPOCH_DATE_TIME_REFERENCE_PROPERTIES = {
"year": 1970, "time_zone_hour": 0, "time_zone_minute": 0}
_DEFAULT = None
@classmethod
def default(cls):
if cls._DEFAULT is None:
cls._DEFAULT = cls()
return cls._DEFAULT
def __init__(self):
self.set_mode()
def set_mode(self, mode=None):
"""Set calendar mode.
mode -- calendar mode, which can be one of the keys in Calendar.MODES.
If None, default to MODE_GREGORIAN.
"""
if not mode:
mode = self.MODE_GREGORIAN
days_in_months, days_in_months_leap = self.MODES[mode.lower()]
if days_in_months_leap is None:
days_in_months_leap = days_in_months
self.DAYS_IN_MONTHS = days_in_months
self.DAYS_IN_MONTHS_LEAP = days_in_months_leap
self.mode = mode
# Recalculate
self.SECONDS_IN_HOUR = self.SECONDS_IN_MINUTE * self.MINUTES_IN_HOUR
self.SECONDS_IN_DAY = self.SECONDS_IN_HOUR * self.HOURS_IN_DAY
self.MINUTES_IN_DAY = self.MINUTES_IN_HOUR * self.HOURS_IN_DAY
self.INDEXED_DAYS_IN_MONTHS = [
(i + 1, days) for i, days in enumerate(self.DAYS_IN_MONTHS)]
self.INDEXED_DAYS_IN_MONTHS_LEAP = [
(i + 1, days) for i, days in enumerate(self.DAYS_IN_MONTHS_LEAP)]
self.REVERSED_INDEXED_DAYS_IN_MONTHS = (
reversed(self.INDEXED_DAYS_IN_MONTHS))
self.REVERSED_INDEXED_DAYS_IN_MONTHS_LEAP = (
reversed(self.INDEXED_DAYS_IN_MONTHS))
self.MONTHS_IN_YEAR = len(self.DAYS_IN_MONTHS)
# No support for MONTHS_IN_YEAR_LEAP (some calendars...)
self.DAYS_IN_YEAR = sum(self.DAYS_IN_MONTHS)
self.ROUGH_DAYS_IN_YEAR = self.DAYS_IN_YEAR
self.DAYS_IN_YEAR_LEAP = sum(self.DAYS_IN_MONTHS_LEAP)
self.HOURS_IN_YEAR = self.DAYS_IN_YEAR * self.HOURS_IN_DAY
self.MINUTES_IN_YEAR = self.DAYS_IN_YEAR * self.MINUTES_IN_DAY
self.SECONDS_IN_YEAR = self.DAYS_IN_YEAR * self.SECONDS_IN_DAY
self.HOURS_IN_YEAR_LEAP = self.DAYS_IN_YEAR_LEAP * self.HOURS_IN_DAY
self.MINUTES_IN_YEAR_LEAP = (
self.DAYS_IN_YEAR_LEAP * self.MINUTES_IN_DAY)
self.SECONDS_IN_YEAR_LEAP = (
self.DAYS_IN_YEAR_LEAP * self.SECONDS_IN_DAY)
def __repr__(self):
return "<%s-%s>" % (type(self).__name__, self.mode)
CALENDAR = Calendar.default()
TIMEPOINT_DUMPER_MAP = {
0: dumpers.TimePointDumper(num_expanded_year_digits=0),
2: dumpers.TimePointDumper(num_expanded_year_digits=2)
}
class BadInputError(ValueError):
"""An error raised when constructor inputs are invalid."""
CONFLICT = "Conflicting input: {0} but have {1}"
INT_CAST = "Invalid input for {0}: {1}: {2}"
INT_REMAINDER = "Non-integer like number for {0}: {1}"
MISSING = "Missing input: {0} needs {1}"
OUT_OF_BOUNDS = "Invalid input (out of bounds): {0}: {1}"
RECURRENCE = "Invalid recurrence info: {0}"
TYPE = "Invalid type for {0}: {1}{2}"
VALUES = "Invalid input for {0}: {1}: allowed: {2}"
def __str__(self):
format_string = self.args[0]
format_args = self.args[1:]
return format_string.format(*format_args)
class TimeRecurrence(object):
"""Represent a recurring duration."""
__slots__ = ("repetitions", "start_point", "duration", "end_point",
"min_point", "max_point", "format_number")
def __init__(self, repetitions=None, start_point=None,
duration=None, end_point=None, min_point=None,
max_point=None):
inputs = (
(repetitions, "repetitions", None, int),
(start_point, "start_point", None, TimePoint),
(duration, "duration", None, Duration),
(end_point, "end_point", None, TimePoint),
(min_point, "min_point", None, TimePoint),
(max_point, "max_point", None, TimePoint)
)
_type_checker(*inputs)
self.repetitions = repetitions
self.start_point = start_point
self.duration = duration
self.end_point = end_point
self.min_point = min_point
self.max_point = max_point
self.format_number = None
if self.duration is None:
# First form.
self.format_number = 1
start_year, start_days = self.start_point.get_ordinal_date()
start_seconds = self.start_point.get_second_of_day()
self.end_point.set_time_zone(self.start_point.time_zone)
end_year, end_days = self.end_point.get_ordinal_date()
end_seconds = self.end_point.get_second_of_day()
diff_days = end_days - start_days
if end_year > start_year:
diff_days += get_days_in_year_range(start_year, end_year - 1)
diff_seconds = end_seconds - start_seconds
if diff_seconds < 0:
diff_days -= 1
diff_seconds += CALENDAR.SECONDS_IN_DAY
if diff_seconds >= CALENDAR.SECONDS_IN_DAY:
diff_days += 1
diff_seconds -= CALENDAR.SECONDS_IN_DAY
if self.repetitions == 1:
self.duration = Duration(years=0)
else:
diff_days_float = diff_days / float(
self.repetitions - 1)
diff_seconds_float = diff_seconds / float(
self.repetitions - 1)
diff_days = int(diff_days_float)
diff_seconds_float += (
diff_days_float - diff_days) * CALENDAR.SECONDS_IN_DAY
self.duration = Duration(
days=diff_days, seconds=diff_seconds_float)
elif self.end_point is None:
# Third form.
self.format_number = 3
if self.repetitions is not None:
point = self.start_point
for i in range(self.repetitions - 1):
point += self.duration
self.end_point = point
elif self.start_point is None:
# Fourth form.
self.format_number = 4
if self.repetitions is not None:
point = self.end_point
for i in range(self.repetitions - 1):
point -= self.duration
self.start_point = point
else:
raise BadInputError(
BadInputError.RECURRENCE,
[i[:2] for i in inputs]
)
def get_is_valid(self, timepoint):
"""Return whether the timepoint is valid for this recurrence."""
if not self._get_is_in_bounds(timepoint):
return False
for iter_timepoint in self.__iter__():
if iter_timepoint == timepoint:
return True
if self.start_point is None and iter_timepoint < timepoint:
return False
if self.end_point is None and iter_timepoint > timepoint:
return False
return False
def get_next(self, timepoint):
"""Return the next timepoint after this timepoint, or None."""
if self.repetitions == 1 or timepoint is None:
return None
next_timepoint = timepoint + self.duration
if self._get_is_in_bounds(next_timepoint):
return next_timepoint
if (self.format_number == 1 and next_timepoint > self.end_point):
diff = next_timepoint - self.end_point
if (2 * diff < self.duration and
self._get_is_in_bounds(self.end_point)):
return self.end_point
return None
def get_prev(self, timepoint):
"""Return the previous timepoint before this timepoint, or None."""
if self.repetitions == 1 or timepoint is None:
return None
prev_timepoint = timepoint - self.duration
if self._get_is_in_bounds(prev_timepoint):
return prev_timepoint
return None
def __getitem__(self, index):
if index < 0 or not isinstance(index, int):
raise IndexError(
"Unsupported index for TimeRecurrence")
for i, point in enumerate(self.__iter__()):
if index == i:
return point
raise IndexError(
"Invalid index for TimeRecurrence")
def _get_is_in_bounds(self, timepoint):
"""Return whether the timepoint is within this recurrence series."""
if timepoint is None:
return False
if self.start_point is not None and timepoint < self.start_point:
return False
if self.min_point is not None and timepoint < self.min_point:
return False
if self.max_point is not None and timepoint > self.max_point:
return False
if self.end_point is not None and timepoint > self.end_point:
return False
return True
def __iter__(self):
if self.start_point is None:
point = self.end_point
in_reverse = True
else:
point = self.start_point
in_reverse = False
if self.repetitions == 1 or not self.duration:
if self._get_is_in_bounds(point):
yield point
point = None
while point is not None:
if self._get_is_in_bounds(point):
yield point
else:
break
if in_reverse:
point = self.get_prev(point)
else:
point = self.get_next(point)
def __str__(self):
if self.repetitions is None:
prefix = "R/"
else:
prefix = "R" + str(self.repetitions) + "/"
if self.format_number == 1:
return prefix + str(self.start_point) + "/" + str(self.end_point)
elif self.format_number == 3:
return prefix + str(self.start_point) + "/" + str(self.duration)
elif self.format_number == 4:
return prefix + str(self.duration) + "/" + str(self.end_point)
return "R/?/?"
def get_tests(self):
"""Return a series of self-tests."""
for recur_expression, result_points in self.TEST_EXPRESSIONS:
yield recur_expression, result_points
class Duration(object):
"""Represent a duration or period of time.
Keyword arguments:
years (default 0): number of calendar years in the duration (an
inexact unit)
months (default 0): number of calendar months in the duration (also
an inexact unit)
weeks (default 0): number of weeks in the duration - cannot be
used in conjunction with other units (use multiples of 7 days
instead)
days (default 0): number of days in the duration
hours (default 0): number of hours in the duration
minutes (default 0): number of minutes in the duration
seconds (default 0): number of seconds in the duration
standardize (default False): boolean that, if True, switches on
adjusting the attributes so that small units have minimal values.
For example, 3664.4 seconds would become 1 hour, 1 minute, and 4.4
seconds. Attributes will not adjust for units that are inexact
(months and years).
"""
DATA_ATTRIBUTES = [
"years", "months", "weeks", "days", "hours", "minutes", "seconds"]
__slots__ = DATA_ATTRIBUTES
def __init__(self, years=0, months=0, weeks=0, days=0,
hours=0.0, minutes=0.0, seconds=0.0, standardize=False):
_type_checker(
(years, "years", int, float, None),
(months, "months", int, float, None),
(weeks, "weeks", int, float, None),
(days, "days", int, float, None),
(hours, "hours", int, float, None),
(minutes, "minutes", int, float, None),
(seconds, "seconds", int, float, None)
)
self.years = years
self.months = months
self.weeks = None
self.days = days
if weeks is not None:
if days is None:
self.days = CALENDAR.DAYS_IN_WEEK * weeks
else:
self.days += CALENDAR.DAYS_IN_WEEK * weeks
self.hours = hours
self.minutes = minutes
self.seconds = seconds
if (not self.years and not self.months and not self.hours and
not self.minutes and not self.seconds and
weeks and not days):
self.weeks = self.days / CALENDAR.DAYS_IN_WEEK
self.years, self.months, self.days = (None, None, None)
self.hours, self.minutes, self.seconds = (None, None, None)
if standardize:
if self.seconds:
num_minutes, self.seconds = divmod(
self.seconds, CALENDAR.SECONDS_IN_MINUTE)
if self.minutes is None:
self.minutes = 0
self.minutes += num_minutes
if self.minutes:
num_hours, self.minutes = divmod(
self.minutes, CALENDAR.MINUTES_IN_HOUR)
if self.hours is None:
self.hours = 0
self.hours += num_hours
if self.hours:
num_days, self.hours = divmod(
self.hours, CALENDAR.HOURS_IN_DAY)
if self.days is None:
self.days = 0
self.days += num_days
def copy(self):
"""Return an unlinked copy of this instance."""
return Duration(
years=self.years, months=self.months, weeks=self.weeks,
days=self.days, hours=self.hours, minutes=self.minutes,
seconds=self.seconds)
def get_days_and_seconds(self):
"""Return a roughly-converted duration in days and seconds.
This cannot be accurate for non-uniform units such as years and
months, and may yield incorrect results if used for comparisons
derived from durations using these units.
Seconds are returned in the range
0 <= seconds < CALENDAR.SECONDS_IN_DAY, which means that a
Duration which has self.seconds = CALENDAR.SECONDS_IN_DAY +
100 will return 1 day, 100 seconds or (1, 100) from this
method.
"""
# TODO: Implement error calculation for the below quantities.
new = self.copy()
new.to_days()
new_days = (new.years * CALENDAR.ROUGH_DAYS_IN_YEAR +
new.months * CALENDAR.ROUGH_DAYS_IN_MONTH +
new.days)
new_seconds = (new.hours * CALENDAR.SECONDS_IN_HOUR +
new.minutes * CALENDAR.SECONDS_IN_MINUTE +
new.seconds)
diff_days, new_seconds = divmod(new_seconds, CALENDAR.SECONDS_IN_DAY)
new_days += diff_days
return new_days, new_seconds
def get_seconds(self):
"""Return a roughly-converted duration in seconds.
This is not rigorous when converting from non-uniform units
such as years and months.
"""
days, seconds = self.get_days_and_seconds()
return days * CALENDAR.SECONDS_IN_DAY + seconds
def get_is_in_weeks(self):
"""Return whether we are in week representation."""
return (self.weeks is not None)
def to_days(self):
"""Convert to day representation rather than weeks."""
if self.get_is_in_weeks():
for attribute in ["years", "months", "hours",
"minutes", "seconds"]:
if getattr(self, attribute) is None:
setattr(self, attribute, 0)
self.days = self.weeks * CALENDAR.DAYS_IN_WEEK
self.weeks = None
def to_weeks(self):
"""Convert to week representation (warning: use with caution)."""
if not self.get_is_in_weeks():
self.weeks = self.days / CALENDAR.DAYS_IN_WEEK
self.years, self.months, self.days = (None, None, None)
self.hours, self.minutes, self.seconds = (None, None, None)
def __abs__(self):
new = self.copy()
for attribute in new.DATA_ATTRIBUTES:
attr_value = getattr(new, attribute)
if attr_value is not None:
setattr(new, attribute, abs(attr_value))
return new
def __add__(self, other):
new = self.copy()
if isinstance(other, Duration):
if new.get_is_in_weeks():
if other.get_is_in_weeks():
new.weeks += other.weeks
return new
new.to_days()
elif other.get_is_in_weeks():
other = other.copy()
other.to_days()
new.years += other.years
new.months += other.months
new.days += other.days
new.hours += other.hours
new.minutes += other.minutes
new.seconds += other.seconds
return new
if isinstance(other, TimePoint):
return other + new
raise TypeError(
"Invalid type for addition: " +
"'%s' should be Duration or TimePoint." %
type(other).__name__
)
def __sub__(self, other):
return self + -1 * other
def __mul__(self, other):
# TODO: support float multiplication?
new = self.copy()
if not isinstance(other, int):
raise TypeError(
"Invalid type for multiplication: " +
"'%s' should be integer." %
type(other).__name__
)
if self.get_is_in_weeks():
new.weeks *= other
return new
new.years *= other
new.months *= other
new.days *= other
new.hours *= other
new.minutes *= other
new.seconds *= other
return new
def __rmul__(self, other):
return self.__mul__(other)
def __floordiv__(self, other):
# TODO: support float division?
new = self.copy()
if not isinstance(other, int):
raise TypeError(
"Invalid type for division: " +
"'%s' should be integer." %
type(other).__name__
)
if self.get_is_in_weeks():
new.weeks //= other
return new
new.years //= other
new.months //= other
new.days //= other
new.hours //= other
new.minutes //= other
new.seconds //= other
def __cmp__(self, other):
if not isinstance(other, Duration):
raise TypeError(
"Invalid type for comparison: " +
"'%s' should be Duration." %
type(other).__name__
)
my_data = self.get_days_and_seconds()
other_data = other.get_days_and_seconds()
return cmp(my_data, other_data)
def __nonzero__(self):
for attr in ["years", "months", "weeks", "days", "hours",
"minutes", "seconds"]:
if getattr(self, attr, None):
return True
return False
def __str__(self):
start_string = "P"
content_string = ""
# Handle negative durations.
is_fully_negative = False
for attribute in self.DATA_ATTRIBUTES:
attr_value = getattr(self, attribute)
if attr_value is not None:
if attr_value > 0:
is_fully_negative = False
break
if attr_value < 0:
is_fully_negative = True
if is_fully_negative:
# Support negative durations as extensions to the standard.
return "-" + str(abs(self))
# Weeks are not combined with any other unit.
if self.get_is_in_weeks():
return (start_string + str(self.weeks) + "W").replace(".", ",")
for prop_, unit in [("years", "Y"), ("months", "M"), ("days", "D"),
("hours", "H"), ("minutes", "M"),
("seconds", "S")]:
prop_val = getattr(self, prop_)
if prop_val:
if int(prop_val) == prop_val:
content_string += str(int(prop_val)) + unit
else:
content_string += str(prop_val) + unit
if prop_ == "days":
content_string += "T"
if content_string == "T":
# No content, zero duration.
content_string = "0Y"
elif content_string.endswith("T"):
# No time unit information, so strip the delimiter.
content_string = content_string[:-1]
total_string = start_string + content_string
return total_string.replace(".", ",")
class TimeZone(Duration):
"""Represent a time zone offset from UTC.
Keyword arguments:
hours, minutes: integers (default 0) denoting the hour and minute
component of the offset from UTC. These may be positive, zero, or
negative, as required. Note that a negative UTC offset should have
both hours and minutes as zero or negative integers.
unknown: a boolean that represents an unknown TimeZone. Some
operations and comparisons may fail when this is True.
"""
__slots__ = ['unknown'] + Duration.__slots__
def __init__(self, hours=0, minutes=0, unknown=False):
self.unknown = unknown
super(TimeZone, self).__init__(hours=hours, minutes=minutes)
def copy(self):
"""Return an unlinked copy of this instance."""
return TimeZone(hours=self.hours, minutes=self.minutes,
unknown=self.unknown)
def __str__(self):
if self.unknown:
return ""
if self.hours == 0 and self.minutes == 0:
return "Z"
else:
time_string = "+%02d:%02d"
if self.hours < 0 or (self.hours == 0 and self.minutes < 0):
time_string = "-%02d:%02d"
return time_string % (abs(self.hours), abs(self.minutes))
def __repr__(self):
return "<isodatetime.data.TimeZone:" + repr(str(self)) + ">"
class TimePoint(object):
"""Represent an instant in time.
An ISO 8601 date/time instant can be represented in three
separate ways:
Calendar date: calendar year, calendar month,
calendar day of the month
Ordinal date: calendar year, calendar day of the year
Week date: calendar (week) year, calendar week,
calendar day of the week (note: week years are not identical to
calendar years).
This class maintains a date/time instant in the original
representation with which it was invoked - so it may be in any of
these formats. See the TimePoint.to_*_date methods for internal
conversions between formats.
Where properties are not given (consistent with ISO 8601 reduced
precision dates), they will be given the expected defaults if
truncation is not specified. For example, if only the year and the
month_of_year is given, the day_of_month will be set to 1.
Time zone information defaults to UTC. It is essential to provide it
unless you are happy with this behaviour. A date/time
representation is ambiguous without it.
Keyword arguments (usually default to None if not provided):
expanded_year_digits (default 0) - an agreed-upon number of extra
digits to represent the year, beyond the default of 4. For example,
a value of 2 would suggest representing the year 2000 as 002000.
year - a positive or negative integer. Note that ISO 8601 implies
using non-zero expanded_year_digits when using negative integers.
Remember we are using the proleptic Gregorian calendar, with a year
zero which does not exist in standard 1 BC => 1 AD usage - so 2 BC
should be represented as -1.
month_of_year - an integer between 1 and 12 inclusive, if using the
calendar date representation.
week_of_year - an integer between 1 and 52/53 (depending on the
year), if using the week date representation.
day_of_year - an integer between 1 and 365/366 (depending on the
year), if using the ordinal date representation.
day_of_month - an integer between 1 and 28/29/30/31 (depending on
the month), if using the calendar date representation.
day_of_week - an integer between 1 and 7, if using the week date
representation.
hour_of_day - an integer between 1 and 24.
hour_of_day_decimal - a float between 0 and 1, if using decimal
accuracy for hours. Note that you should not provide lower units
such as minute_of_hour or second_of_minute when using this.
minute_of_hour - an integer between 0 and 59.
minute_of_hour_decimal - a float between 0 and 1, if using decimal
accuracy for minutes. Note that you should not provide lower units
such as second_of_minute when using this.
second_of_minute - an integer between 0 and 59 (note: no support
for leap seconds at 60 yet)
second_of_minute_decimal - a float between 0 and 1, if using decimal
accuracy for seconds.
time_zone_hour - (default 0) an integer denoting the hour time zone
offset from UTC. Note that unless this is a truncated
representation, 0 will be assumed if this is not provided.
time_zone_minute - (default 0) an integer between 0 and 59 denoting
the minute component of the time zone offset from UTC.
dump_format - a custom format string to control the stringification
of the timepoint. See isodatetime.parser_spec for more details.
truncated - (default False) a boolean denoting whether the
date/time instant has purposefully incomplete information
(ISO 8601:2000 truncation).
truncated_dump_format - a custom format string to control the
stringification of the timepoint if it is truncated. See
isodatetime.parser_spec for more details.
truncated_property - a string that can either be "year_of_decade"
or "year_of_century". This is used for truncated representations to
distinguish between the two ways of truncating the year.
is_empty_instance - if True, do not set any properties yet. These
should be set as part of a copy operation.
"""
DATA_ATTRIBUTES = [
"expanded_year_digits", "year", "month_of_year",
"day_of_year", "day_of_month", "day_of_week",
"week_of_year", "hour_of_day", "minute_of_hour",
"second_of_minute", "truncated", "truncated_property",
"dump_format", "time_zone"
]
__slots__ = DATA_ATTRIBUTES + ["truncated_dump_format"]
def __init__(self, expanded_year_digits=0, year=None, month_of_year=None,
week_of_year=None, day_of_year=None, day_of_month=None,
day_of_week=None, hour_of_day=None, hour_of_day_decimal=None,
minute_of_hour=None, minute_of_hour_decimal=None,
second_of_minute=None, second_of_minute_decimal=None,
time_zone_hour=None, time_zone_minute=None,
dump_format=None, truncated=False,
truncated_dump_format=None, truncated_property=None,
is_empty_instance=False):
if is_empty_instance:
# This has been created for a copy - set properties later.
return
_type_checker(
(expanded_year_digits, "expanded_year_digits", int),
(year, "year", None, int),
(month_of_year, "month_of_year", None, int),
(week_of_year, "week_of_year", None, int),
(day_of_year, "day_of_year", None, int),
(day_of_month, "day_of_month", None, int),
(day_of_week, "day_of_week", None, int),
(hour_of_day, "hour_of_day", None, int, float),
(hour_of_day_decimal, "hour_of_day_decimal", None, float),
(minute_of_hour, "minute_of_hour", None, int, float),
(minute_of_hour_decimal, "minute_of_hour_decimal", None, float),
(second_of_minute, "second_of_minute", None, int, float),
(second_of_minute_decimal, "second_of_minute_decimal", None,
float),
(time_zone_hour, "time_zone_hour", None, int),
(time_zone_minute, "time_zone_minute", None, int)
)
if (dump_format is not None and not
isinstance(dump_format, basestring)):
raise BadInputError(
BadInputError.TYPE,
"dump_format", repr(dump_format), type(dump_format))
if (truncated_dump_format is not None and not
isinstance(truncated_dump_format, basestring)):
raise BadInputError(
BadInputError.TYPE,
"truncated_dump_format", repr(truncated_dump_format),
type(truncated_dump_format)
)
if (truncated_property is not None and
truncated_property not in ["year_of_decade",
"year_of_century"]):
raise BadInputError(
BadInputError.VALUES, "truncated_property",
repr(truncated_property),
"'year_of_decade' or 'year_of_century'")
self.dump_format = dump_format
self.expanded_year_digits = _int_caster(expanded_year_digits,
"expanded_year_digits")
self.truncated = truncated
self.truncated_dump_format = truncated_dump_format
self.truncated_property = truncated_property
self.year = _int_caster(year, "year", allow_none=True)
self.month_of_year = _int_caster(month_of_year, "year",
allow_none=True)
self.day_of_year = _int_caster(day_of_year, "day_of_year",
allow_none=True)
self.day_of_month = _int_caster(day_of_month, "day_of_month",
allow_none=True)
self.day_of_week = _int_caster(day_of_week, "day_of_week",
allow_none=True)
self.week_of_year = _int_caster(week_of_year, "week_of_year",
allow_none=True)
self.hour_of_day = _int_caster(hour_of_day, "hour_of_day",
allow_none=True)
if hour_of_day_decimal is not None:
if self.hour_of_day is None:
raise BadInputError(
BadInputError.MISSING, "hour_of_day_decimal",
"hour_of_day")
self.hour_of_day += float(hour_of_day_decimal)
if minute_of_hour is not None:
raise BadInputError(
BadInputError.CONFLICT, "minute_of_hour",
"hour_of_day_decimal")
if second_of_minute is not None:
raise BadInputError(
BadInputError.CONFLICT, "second_of_minute",
"hour_of_day_decimal")
if minute_of_hour_decimal is not None:
if minute_of_hour is None:
raise BadInputError(
BadInputError.MISSING, "minute_of_hour_decimal",
"minute_of_hour")
self.minute_of_hour = _int_caster(
minute_of_hour, "minute_of_hour")
self.minute_of_hour += float(minute_of_hour_decimal)
if second_of_minute is not None:
raise BadInputError(
BadInputError.CONFLICT, "second_of_minute",
"minute_of_hour_decimal")
else:
self.minute_of_hour = _int_caster(
minute_of_hour, "minute_of_hour", allow_none=True)
if second_of_minute_decimal is not None:
if second_of_minute is None:
raise BadInputError(
BadInputError.MISSING,
"second_of_minute_decimal",
"second_of_minute")
self.second_of_minute = _int_caster(second_of_minute,
"second_of_minute")
self.second_of_minute += float(second_of_minute_decimal)
else:
self.second_of_minute = _int_caster(second_of_minute,
"second_of_minute",
allow_none=True)
if not self.truncated:
if self.hour_of_day is None:
self.hour_of_day = 0
if hour_of_day_decimal is None and self.minute_of_hour is None:
self.minute_of_hour = 0
if (hour_of_day_decimal is None and
minute_of_hour_decimal is None and
self.second_of_minute is None):
self.second_of_minute = 0
self.time_zone = TimeZone()
has_unknown_tz = True
if time_zone_hour is not None:
has_unknown_tz = False
self.time_zone.hours = _int_caster(time_zone_hour,
"time_zone_hour")
if time_zone_minute is not None:
has_unknown_tz = False
self.time_zone.minutes = _int_caster(time_zone_minute,
"time_zone_minute")
self.time_zone.unknown = self.truncated and has_unknown_tz
if not self.truncated:
# Reduced precision date - e.g. 1970 - assume Jan 1, etc.
if (self.month_of_year is None and self.week_of_year is None and
self.day_of_year is None):
self.month_of_year = 1
if self.month_of_year is not None and self.day_of_month is None:
self.day_of_month = 1
if self.week_of_year is not None and self.day_of_week is None:
self.day_of_week = 1
def get_is_calendar_date(self):
"""Return whether this is in years, month-of-year, day-of-month."""
return self.month_of_year is not None
def get_is_ordinal_date(self):
"""Return whether this is in years, day-of-the year format."""
return self.day_of_year is not None
def get_is_week_date(self):
"""Return whether this is in years, week-of-year, day-of-week."""
return self.week_of_year is not None
def get_calendar_date(self):
"""Return the year, month-of-year and day-of-month for this date."""
if self.get_is_calendar_date():
return self.year, self.month_of_year, self.day_of_month
if self.get_is_ordinal_date():
return get_calendar_date_from_ordinal_date(self.year,
self.day_of_year)
if self.get_is_week_date():
return get_calendar_date_from_week_date(self.year,
self.week_of_year,
self.day_of_week)
def get_hour_minute_second(self):
"""Return the time of day expressed in hours, minutes, seconds."""
hour_of_day = self.hour_of_day
minute_of_hour = self.minute_of_hour
second_of_minute = self.second_of_minute
if second_of_minute is None:
if minute_of_hour is None:
hour_decimals = hour_of_day - int(hour_of_day)
hour_of_day = float(int(hour_of_day))
minute_of_hour = CALENDAR.MINUTES_IN_HOUR * hour_decimals
minute_decimals = minute_of_hour - int(minute_of_hour)
minute_of_hour = float(int(minute_of_hour))
second_of_minute = CALENDAR.SECONDS_IN_MINUTE * minute_decimals
return hour_of_day, minute_of_hour, second_of_minute
def get_ordinal_date(self):
"""Return the year, day-of-year for this date."""
if self.get_is_calendar_date():
return get_ordinal_date_from_calendar_date(self.year,
self.month_of_year,
self.day_of_month)
if self.get_is_ordinal_date():
return self.year, self.day_of_year
if self.get_is_week_date():
return get_ordinal_date_from_week_date(self.year,
self.week_of_year,
self.day_of_week)
def get(self, property_name):
"""Return a calculated value for property name."""
if property_name == "expanded_year_digits":
return abs(self.year) / 10000
if property_name == "year_sign":
return "+" if self.year >= 0 else "-"
if property_name == "century":
return (abs(self.year) % 10000) // 100
if property_name == "year_of_century":
return abs(self.year) % 100
if property_name == "month_of_year":
if self.month_of_year is not None:
return self.month_of_year
return self.get_calendar_date()[1]
if property_name == "day_of_year":
if self.day_of_year is not None:
return self.day_of_year
return self.get_ordinal_date()[1]
if property_name == "day_of_month":
if self.day_of_month is not None:
return self.day_of_month
return self.get_calendar_date()[2]
if property_name == "week_of_year":
if self.week_of_year is not None:
return self.week_of_year
return self.get_week_date()[1]
if property_name == "day_of_week":
if self.day_of_week is not None:
return self.day_of_week
return self.get_week_date()[2]
if property_name == "year_of_decade":
return abs(self.year) % 10
if property_name == "minute_of_hour":
if self.minute_of_hour is None:
return self.get_hour_minute_second()[1]
return int(self.minute_of_hour)
if property_name == "hour_of_day":
return int(self.hour_of_day)
if property_name == "hour_of_day_decimal_string":
string = "%f" % (float(self.hour_of_day) - int(self.hour_of_day))
string = string.replace("0.", "", 1).rstrip("0")
if not string:
return "0"
return string
if property_name == "minute_of_hour_decimal_string":
string = "%f" % (float(self.minute_of_hour) -
int(self.minute_of_hour))
string = string.replace("0.", "", 1).rstrip("0")
if not string:
return "0"
return string
if property_name == "second_of_minute":
if self.second_of_minute is None:
return self.get_hour_minute_second()[2]
return int(self.second_of_minute)
if property_name == "second_of_minute_decimal_string":
string = "%f" % (float(self.second_of_minute) -
int(self.second_of_minute))
string = string.replace("0.", "", 1).rstrip("0")
if not string:
return "0"
return string
if property_name == "time_zone_minute_abs":
return abs(self.time_zone.minutes)
if property_name == "time_zone_hour_abs":
return abs(self.time_zone.hours)
if property_name == "time_zone_sign":
if self.time_zone.hours < 0 or self.time_zone.minutes < 0:
return "-"
return "+"
if property_name == "seconds_since_unix_epoch":
reference_timepoint = TimePoint(
**CALENDAR.UNIX_EPOCH_DATE_TIME_REFERENCE_PROPERTIES)
days, seconds = (
self - reference_timepoint).get_days_and_seconds()
# N.B. This needs altering if we implement leap seconds.
return str(int(CALENDAR.SECONDS_IN_DAY * days + seconds))
raise NotImplementedError(property_name)
def get_second_of_day(self):
"""Return the seconds elapsed since the start of the day."""
second_of_day = 0
if self.second_of_minute is not None:
second_of_day += self.second_of_minute
if self.minute_of_hour is not None:
second_of_day += self.minute_of_hour * CALENDAR.SECONDS_IN_MINUTE
second_of_day += self.hour_of_day * CALENDAR.SECONDS_IN_HOUR
return second_of_day
def get_time_zone(self):
"""Return the time_zone offset from UTC as a duration."""
return self.time_zone
def get_time_zone_utc(self):
"""Return whether the time zone is explicitly in UTC."""
if self.time_zone.unknown:
return False
return self.time_zone.hours == 0 and self.time_zone.minutes == 0
def get_week_date(self):
"""Return the year, week-of-year, day-of-week for this date."""
if self.get_is_calendar_date():
return get_week_date_from_calendar_date(self.year,
self.month_of_year,
self.day_of_month)
if self.get_is_ordinal_date():
return get_week_date_from_ordinal_date(self.year,
self.day_of_year)
if self.get_is_week_date():
return self.year, self.week_of_year, self.day_of_week
def apply_time_zone_offset(self, offset):
"""Apply a time zone shift represented by a Duration."""
if offset.minutes:
if self.minute_of_hour is None:
self.hour_of_day += (
offset.minutes / float(CALENDAR.MINUTES_IN_HOUR))
else:
self.minute_of_hour += offset.minutes
self._tick_over()
if offset.hours:
self.hour_of_day += offset.hours
self._tick_over()
def get_time_zone_offset(self, other):
"""Get the difference in hours and minutes between time zones."""
if other.get_time_zone().unknown or self.get_time_zone().unknown:
return Duration()
return other.get_time_zone() - self.get_time_zone()
def set_time_zone(self, dest_time_zone):
"""Adjust to the new time zone.
dest_time_zone should be a TimeZone instance expressing difference
from UTC, if any.
"""
if dest_time_zone.unknown:
return
self.apply_time_zone_offset(dest_time_zone - self.get_time_zone())
self.time_zone = dest_time_zone
def set_time_zone_to_local(self):
"""Set the time zone to the local time zone, if it's not already."""
local_hours, local_minutes = timezone.get_local_time_zone()
self.set_time_zone(TimeZone(hours=local_hours, minutes=local_minutes))
def set_time_zone_to_utc(self):
"""Set the time zone to UTC, if it's not already."""
self.set_time_zone(TimeZone(hours=0, minutes=0))
def to_calendar_date(self):
"""Reformat the date in years, month-of-year, day-of-month."""
year, month, day = self.get_calendar_date()
self.year, self.month_of_year, self.day_of_month = year, month, day
self.day_of_year = None
self.week_of_year = None
self.day_of_week = None
return self
def to_hour_minute_second(self):
"""Expand time fractions into hours, minutes, seconds."""
hour, minute, second = self.get_hour_minute_second()
self.hour_of_day = hour
self.minute_of_hour = minute
self.second_of_minute = second
def to_week_date(self):
"""Reformat the date in years, week-of-year, day-of-week."""
self.year, self.week_of_year, self.day_of_week = self.get_week_date()
self.day_of_year = None
self.month_of_year = None
self.day_of_month = None
return self
def to_ordinal_date(self):
"""Reformat the date in years and day-of-the-year."""
self.year, self.day_of_year = self.get_ordinal_date()
self.month_of_year = None
self.day_of_month = None
self.week_of_year = None
self.day_of_week = None
return self
def get_largest_truncated_property_name(self):
"""Return the largest unit in a truncated representation."""
if not self.truncated:
return None
prop_dict = self.get_truncated_properties()
for attr in ["year_of_century", "year_of_decade", "month_of_year",
"week_of_year", "day_of_year", "day_of_month",
"day_of_week", "hour_of_day", "minute_of_hour",
"second_of_minute"]:
if attr in prop_dict:
return attr
return None
def get_truncated_properties(self):
"""Return a map of properties if this is a truncated representation."""
if not self.truncated:
return None
props = {}
if self.truncated_property == "year_of_decade":
props.update({"year_of_decade": self.year % 10})
if self.truncated_property == "year_of_century":
props.update({"year_of_century": self.year % 100})
for attr in ["month_of_year", "week_of_year", "day_of_year",
"day_of_month", "day_of_week", "hour_of_day",
"minute_of_hour", "second_of_minute"]:
value = getattr(self, attr)
if value is not None:
props.update({attr: value})
return props
def add_truncated(self, year_of_century=None, year_of_decade=None,
month_of_year=None, week_of_year=None, day_of_year=None,
day_of_month=None, day_of_week=None, hour_of_day=None,
minute_of_hour=None, second_of_minute=None):
"""Combine this TimePoint with truncated time properties."""
new = self.copy()
if hour_of_day is not None and minute_of_hour is None:
minute_of_hour = 0
if ((hour_of_day is not None or minute_of_hour is not None) and
second_of_minute is None):
second_of_minute = 0
if second_of_minute is not None or minute_of_hour is not None:
new.to_hour_minute_second()
if second_of_minute is not None:
while new.second_of_minute != second_of_minute:
new.second_of_minute += 1.0
new._tick_over()
if minute_of_hour is not None:
while new.minute_of_hour != minute_of_hour:
new.minute_of_hour += 1.0
new._tick_over()
if hour_of_day is not None:
while new.hour_of_day != hour_of_day:
new.hour_of_day += 1.0
new._tick_over()
if day_of_week is not None:
new.to_week_date()
while new.day_of_week != day_of_week:
new.day_of_week += 1
new._tick_over()
if day_of_month is not None:
new.to_calendar_date()
while new.day_of_month != day_of_month:
new.day_of_month += 1
new._tick_over()
if day_of_year is not None:
new.to_ordinal_date()
while new.day_of_year != day_of_year:
new.day_of_year += 1
new._tick_over()
if week_of_year is not None:
new.to_week_date()
while new.week_of_year != week_of_year:
new.week_of_year += 1
new._tick_over()
if month_of_year is not None:
new.to_calendar_date()
while new.month_of_year != month_of_year:
new.month_of_year += 1
new._tick_over()
if year_of_decade is not None:
new.to_calendar_date()
new_year_of_decade = new.year % 10
while new_year_of_decade != year_of_decade:
new.year += 1
new_year_of_decade = new.year % 10
if year_of_century is not None:
new.to_calendar_date()
new_year_of_century = new.year % 100
while new_year_of_century != year_of_century:
new.year += 1
new_year_of_century = new.year % 100
return new
def __add__(self, other, no_copy=False):
if isinstance(other, TimePoint):
if self.truncated and not other.truncated:
new = self.copy()
new_other = other.copy()
prev_time_zone = new_other.get_time_zone()
new_other.set_time_zone(new.get_time_zone())
new_other = new_other.add_truncated(
**new.get_truncated_properties())
new_other.set_time_zone(prev_time_zone)
return new_other
if other.truncated and not self.truncated:
return other + self
if not isinstance(other, Duration):
raise TypeError(
"Invalid addition: can only add Duration or "
"truncated TimePoint to TimePoint.")
duration = other
if duration.get_is_in_weeks():
duration = other.copy()
duration.to_days()
if no_copy:
new = self
else:
new = self.copy()
if duration.seconds:
if new.second_of_minute is None:
if new.minute_of_hour is None:
new.hour_of_day += (
duration.seconds / float(CALENDAR.SECONDS_IN_HOUR))
else:
new.minute_of_hour += (
duration.seconds / float(CALENDAR.SECONDS_IN_MINUTE))
else:
new.second_of_minute += duration.seconds
new._tick_over()
if duration.minutes:
if new.minute_of_hour is None:
new.hour_of_day += (
duration.minutes / float(CALENDAR.MINUTES_IN_HOUR))
else:
new.minute_of_hour += duration.minutes
new._tick_over()
if duration.hours:
new.hour_of_day += duration.hours
new._tick_over()
if duration.days:
if new.get_is_calendar_date():
new.day_of_month += duration.days
elif new.get_is_ordinal_date():
new.day_of_year += duration.days
else:
new.day_of_week += duration.days
new._tick_over()
if duration.months:
# This is the dangerous one...
new._add_months(duration.months)
if duration.years:
new.year += duration.years
if new.get_is_calendar_date():
month_index = (
(new.month_of_year - 1) % CALENDAR.MONTHS_IN_YEAR)
if get_is_leap_year(new.year):
max_day_in_new_month = (
CALENDAR.DAYS_IN_MONTHS_LEAP[month_index])
else:
max_day_in_new_month = (
CALENDAR.DAYS_IN_MONTHS[month_index])
if new.day_of_month > max_day_in_new_month:
# For example, when Feb 29 - 1 year = Feb 28.
new.day_of_month = max_day_in_new_month
elif new.get_is_ordinal_date():
max_days_in_year = get_days_in_year(new.year)
if max_days_in_year > new.day_of_year:
new.day_of_year = max_days_in_year
elif new.get_is_week_date():
max_weeks_in_year = get_weeks_in_year(new.year)
if max_weeks_in_year > new.week_of_year:
new.week_of_year = max_weeks_in_year
return new
def copy(self):
"""Copy this TimePoint without leaving references."""
dummy_timepoint = TimePoint(is_empty_instance=True)
for attr in self.DATA_ATTRIBUTES:
setattr(dummy_timepoint, attr, getattr(self, attr))
dummy_timepoint.time_zone = self.time_zone.copy()
return dummy_timepoint
def get_props(self):
"""Return the data properties of this TimePoint."""
hash_ = []
for attr in self.DATA_ATTRIBUTES:
value = getattr(self, attr, None)
if callable(getattr(value, "copy", None)):
value = value.copy()
hash_.append((attr, value))
return hash_
def __cmp__(self, other):
if not isinstance(other, TimePoint):
raise TypeError(
"Invalid comparison type '%s' - should be TimePoint." %
type(other).__name__
)
if self.truncated != other.truncated:
raise TypeError(
"Cannot compare truncated to non-truncated " +
"TimePoint: %s, %s" % (self, other))
if self.get_props() == other.get_props():
return 0
if self.truncated:
for attribute in self.DATA_ATTRIBUTES:
other_attr = getattr(other, attribute)
self_attr = getattr(self, attribute)
if other_attr != self_attr:
return cmp(self_attr, other_attr)
return 0
other = other.copy()
other.set_time_zone(self.get_time_zone())
if self.get_is_calendar_date():
my_date = self.get_calendar_date()
other_date = other.get_calendar_date()
else:
my_date = self.get_ordinal_date()
other_date = other.get_ordinal_date()
my_datetime = list(my_date) + [self.get_second_of_day()]
other_datetime = list(other_date) + [other.get_second_of_day()]
return cmp(my_datetime, other_datetime)
def __sub__(self, other):
if isinstance(other, TimePoint):
other = other.copy()
other.set_time_zone(self.get_time_zone())
my_year, my_day_of_year = self.get_ordinal_date()
other_year, other_day_of_year = other.get_ordinal_date()
diff_year = my_year - other_year
diff_day = my_day_of_year - other_day_of_year
if my_year > other_year:
diff_day += get_days_in_year_range(other_year, my_year - 1)
else:
diff_day -= get_days_in_year_range(my_year, other_year - 1)
if diff_day < 0:
return -1 * (other - self)
my_hour, my_minute, my_second = self.get_hour_minute_second()
other_hour, other_minute, other_second = (
other.get_hour_minute_second())
diff_hour = my_hour - other_hour
diff_minute = my_minute - other_minute
diff_second = my_second - other_second
if diff_second < 0:
diff_minute -= 1
diff_second += CALENDAR.SECONDS_IN_MINUTE
if diff_minute < 0:
diff_hour -= 1
diff_minute += CALENDAR.MINUTES_IN_HOUR
if diff_hour < 0:
diff_day -= 1
diff_hour += CALENDAR.HOURS_IN_DAY
return Duration(
days=diff_day, hours=diff_hour, minutes=diff_minute,
seconds=diff_second)
if not isinstance(other, Duration):
raise TypeError(
"Invalid subtraction type " +
"'%s' - should be Duration." %
type(other).__name__
)
duration = other
return self.__add__(duration * -1)
def _add_months(self, num_months):
"""Add an amount of months to the representation."""
if num_months == 0:
return
was_ordinal_date = False
was_week_date = False
if not self.get_is_calendar_date():
if self.get_is_ordinal_date():
was_ordinal_date = True
if self.get_is_week_date():
was_week_date = True
self.to_calendar_date()
for i in range(abs(num_months)):
if num_months > 0:
self.month_of_year += 1
if self.month_of_year > CALENDAR.MONTHS_IN_YEAR:
self.month_of_year -= CALENDAR.MONTHS_IN_YEAR
self.year += 1
if num_months < 0:
self.month_of_year -= 1
if self.month_of_year < 1:
self.month_of_year += CALENDAR.MONTHS_IN_YEAR
self.year -= 1
month_index = (self.month_of_year - 1) % CALENDAR.MONTHS_IN_YEAR
if get_is_leap_year(self.year):
max_day_in_new_month = (
CALENDAR.DAYS_IN_MONTHS_LEAP[month_index])
else:
max_day_in_new_month = (
CALENDAR.DAYS_IN_MONTHS[month_index])
if self.day_of_month > max_day_in_new_month:
# For example, when 31 March + 1 month = 30 April.
self.day_of_month = max_day_in_new_month
self._tick_over()
if was_ordinal_date:
self.to_ordinal_date()
if was_week_date:
self.to_week_date()
def _tick_over(self):
"""Correct all the units going from smallest to largest."""
if (self.hour_of_day is not None and
self.minute_of_hour is not None):
hours_remainder = self.hour_of_day - int(self.hour_of_day)
self.hour_of_day -= hours_remainder
self.minute_of_hour += (
hours_remainder * CALENDAR.MINUTES_IN_HOUR)
if (self.minute_of_hour is not None and
self.second_of_minute is not None):
minutes_remainder = self.minute_of_hour - int(self.minute_of_hour)
self.minute_of_hour -= minutes_remainder
self.second_of_minute += (
minutes_remainder * CALENDAR.SECONDS_IN_MINUTE)
if self.second_of_minute is not None:
num_minutes, seconds = divmod(self.second_of_minute,
CALENDAR.SECONDS_IN_MINUTE)
self.minute_of_hour += num_minutes
self.second_of_minute = seconds
if self.minute_of_hour is not None:
num_hours, minutes = divmod(self.minute_of_hour,
CALENDAR.MINUTES_IN_HOUR)
self.hour_of_day += num_hours
self.minute_of_hour = minutes
if self.hour_of_day is not None:
num_days, hours = divmod(self.hour_of_day, CALENDAR.HOURS_IN_DAY)
num_days = int(num_days)
if self.day_of_week is not None:
self.day_of_week += num_days
elif self.day_of_month is not None:
self.day_of_month += num_days
elif self.day_of_year is not None:
self.day_of_year += num_days
self.hour_of_day = hours
if self.day_of_week is not None:
num_weeks, days = divmod(
self.day_of_week - 1, CALENDAR.DAYS_IN_WEEK)
self.week_of_year += num_weeks
self.day_of_week = days + 1
if self.day_of_month is not None:
self._tick_over_day_of_month()
if self.day_of_year is not None:
while self.day_of_year < 1:
days_in_last_year = get_days_in_year(self.year - 1)
self.day_of_year += days_in_last_year
self.year -= 1
while self.day_of_year > get_days_in_year(self.year):
days_in_next_year = get_days_in_year(self.year + 1)
self.day_of_year -= days_in_next_year
self.year += 1
if self.week_of_year is not None:
while self.week_of_year < 1:
weeks_in_last_year = get_weeks_in_year(self.year - 1)
self.week_of_year += weeks_in_last_year
self.year -= 1
while self.week_of_year > get_weeks_in_year(self.year):
weeks_in_this_year = get_weeks_in_year(self.year)
self.week_of_year -= weeks_in_this_year
self.year += 1
if self.month_of_year is not None:
while self.month_of_year < 1:
self.month_of_year += CALENDAR.MONTHS_IN_YEAR
self.year -= 1
while self.month_of_year > CALENDAR.MONTHS_IN_YEAR:
self.month_of_year -= CALENDAR.MONTHS_IN_YEAR
self.year += 1
def _tick_over_day_of_month(self):
if self.day_of_month < 1:
num_days = 2
for month, day in iter_months_days(
self.year,
month_of_year=self.month_of_year,
day_of_month=1, in_reverse=True):
num_days -= 1
if num_days == self.day_of_month:
self.month_of_year = month
self.day_of_month = day
break
else:
start_year = self.year
while num_days != self.day_of_month:
start_year -= 1
for month, day in iter_months_days(
start_year, in_reverse=True):
num_days -= 1
if num_days == self.day_of_month:
break
self.year = start_year
self.month_of_year = month
self.day_of_month = day
else:
month_index = (self.month_of_year - 1) % CALENDAR.MONTHS_IN_YEAR
if get_is_leap_year(self.year):
max_day_in_month = CALENDAR.DAYS_IN_MONTHS_LEAP[month_index]
else:
max_day_in_month = CALENDAR.DAYS_IN_MONTHS[month_index]
if self.day_of_month > max_day_in_month:
num_days = 0
for month, day in iter_months_days(
self.year,
month_of_year=self.month_of_year,
day_of_month=1):
num_days += 1
if num_days == self.day_of_month:
self.month_of_year = month
self.day_of_month = day
break
else:
start_year = self.year
while num_days != self.day_of_month:
start_year += 1
for month, day in iter_months_days(start_year):
num_days += 1
if num_days == self.day_of_month:
self.year = start_year
self.month_of_year = month
self.day_of_month = day
return
def __str__(self, override_custom_dump_format=False,
strftime_format=None):
if self.expanded_year_digits not in TIMEPOINT_DUMPER_MAP:
TIMEPOINT_DUMPER_MAP[self.expanded_year_digits] = (
dumpers.TimePointDumper(
self.expanded_year_digits))
dumper = TIMEPOINT_DUMPER_MAP[self.expanded_year_digits]
if strftime_format is not None:
return dumper.strftime(self, strftime_format)
if self.truncated:
if self.truncated_dump_format and not override_custom_dump_format:
return dumper.dump(self, self.truncated_dump_format)
return dumper.dump(self, self._get_truncated_dump_format())
if self.dump_format and not override_custom_dump_format:
return dumper.dump(self, self.dump_format)
return dumper.dump(self, self._get_dump_format())
def strftime(self, strftime_format):
"""Implement equivalent of Python 2's datetime.datetime.strftime.
Dump based on the format given in the strftime_format string.
"""
return self.__str__(strftime_format=strftime_format)
def _get_dump_format(self):
year_digits = 4 + self.expanded_year_digits
year_string = "%0" + str(year_digits) + "d"
if self.expanded_year_digits:
if self.year < 0:
year_string = "-" + year_string % abs(self.year)
else:
year_string = "+" + year_string % abs(self.year)
elif self.year is not None and self.year < 0:
raise OverflowError(
"Year %s can only be represented in expanded format" %
self.year
)
elif self.year is not None:
year_string = year_string % self.year
if self.get_is_calendar_date():
date_string = year_string + "-MM-DD"
if self.get_is_ordinal_date():
date_string = year_string + "-DDD"
if self.get_is_week_date():
date_string = year_string + "-Www-D"
time_string = "Thh"
if self.minute_of_hour is None:
time_string += ",ii"
else:
time_string += ":mm"
if self.second_of_minute is None:
time_string += ",nn"
else:
seconds_int = int(self.second_of_minute)
time_string += ":ss"
if seconds_int != self.second_of_minute:
time_string += ",tt"
if time_string:
if self.time_zone.hours == 0 and self.time_zone.minutes == 0:
time_string += "Z"
else:
time_string += u"+hh:mm"
return date_string + time_string
def _get_truncated_dump_format(self):
year_string = "-"
if self.truncated_property == "year_of_decade":
year_string = "-" + "z"
elif self.truncated_property == "year_of_century":
if self.day_of_month is None and self.month_of_year is not None:
year_string = "-YY"
else:
year_string = "YY"
date_string = year_string
if self.month_of_year is not None:
date_string = year_string + "-MM"
if self.day_of_month is not None:
date_string += "-DD"
elif self.day_of_month is not None:
if year_string == "-":
date_string = year_string + "--DD"
else:
date_string = year_string + "-DD"
if self.day_of_year is not None:
day_string = "DDD"
if year_string == "-":
date_string = year_string + day_string
else:
date_string = year_string + "-" + day_string
if self.week_of_year is not None:
if year_string == "-":
date_string = year_string + "Www"
else:
date_string = year_string + "-Www"
if self.day_of_week is not None:
date_string += "-D"
elif self.day_of_week is not None:
if year_string == "-":
date_string = year_string + "W-D"
else:
date_string = year_string + "-W-D"
time_string = ""
if (self.hour_of_day is None and
(self.minute_of_hour is not None or
self.second_of_minute is not None)):
time_string = "T-"
elif (self.hour_of_day is not None and
int(self.hour_of_day) != self.hour_of_day):
time_string = "Thh,ii"
elif self.hour_of_day is not None:
time_string = "Thh"
if self.minute_of_hour is None and self.second_of_minute is not None:
time_string += "-"
elif (self.minute_of_hour is not None and
int(self.minute_of_hour) != self.minute_of_hour):
if self.hour_of_day is not None:
time_string += ":"
time_string += "mm,nn"
elif self.minute_of_hour is not None:
if self.hour_of_day is not None:
time_string += ":"
time_string += "mm"
if self.second_of_minute is not None:
seconds_int = int(self.second_of_minute)
if self.minute_of_hour is not None:
time_string += ":"
time_string += "ss"
if seconds_int != self.second_of_minute:
time_string += ",tt"
if time_string:
if self.time_zone.hours == 0 and self.time_zone.minutes == 0:
time_string += "Z"
else:
time_string += u"+hh:mm"
if date_string == "YY":
date_string = "-YY"
time_string = time_string.replace(":", "")
if date_string == "-":
date_string = ""
return date_string + time_string
__repr__ = __str__
def _format_remainder(float_time_number):
"""Format a floating point remainder of a time unit."""
string = "," + ("%f" % float_time_number)[2:].rstrip("0")
if string == ",":
return ""
return string
@util.cache_results
def get_is_leap_year(year):
"""Return if year is a leap year."""
year_is_leap = False
for factor, is_leap_factor in CALENDAR.LEAP_YEAR_FACTOR_TRUTHS:
if year % factor == 0:
year_is_leap = is_leap_factor
return year_is_leap
def get_days_in_year_range(start_year, end_year):
"""Return the number of days within this year range (inclusive)."""
return _get_days_in_year_range(start_year, end_year,
calendar_mode=CALENDAR.mode)
@util.cache_results
def _get_days_in_year_range(start_year, end_year, calendar_mode=None):
"""Return the number of days within this year range (inclusive).
If end_year > start_year, return the days in start_year plus
the days in the intervening years before end_year, plus the
days in end_year.
If end_year == start_year, return the days in start_year.
If end_year < start_year, return 0.
"""
# Get the number of days discounting leap years.
if start_year == end_year:
return get_days_in_year(start_year)
if start_year > end_year:
return 0
days = (end_year + 1 - start_year) * CALENDAR.DAYS_IN_YEAR
diff_days_leap = (CALENDAR.DAYS_IN_YEAR_LEAP - CALENDAR.DAYS_IN_YEAR)
for factor, is_leap_factor in CALENDAR.LEAP_YEAR_FACTOR_TRUTHS:
num_corrections = 0
if start_year % factor == 0:
num_corrections += 1
if end_year != start_year and end_year % factor == 0:
num_corrections += 1
factor_start_year = start_year + 1
while (factor_start_year % factor != 0 and
factor_start_year < end_year):
factor_start_year += 1
if factor_start_year < end_year:
num_corrections += 1
num_corrections += (
end_year - (factor_start_year + 1)) / factor
if is_leap_factor:
days += num_corrections * diff_days_leap
else:
days -= num_corrections * diff_days_leap
return days
def get_days_in_year(year):
"""Return the number of days in this particular year."""
return _get_days_in_year(year, calendar_mode=CALENDAR.mode)
@util.cache_results
def _get_days_in_year(year, calendar_mode=None):
"""Return the number of days in this particular year."""
if get_is_leap_year(year):
return CALENDAR.DAYS_IN_YEAR_LEAP
return CALENDAR.DAYS_IN_YEAR
def get_weeks_in_year(year):
"""Return the number of calendar weeks in this week date year."""
return _get_weeks_in_year(year, calendar_mode=CALENDAR.mode)
@util.cache_results
def _get_weeks_in_year(year, calendar_mode=None):
"""Return the number of calendar weeks in this week date year."""
cal_year, cal_ord_days = get_ordinal_date_week_date_start(year)
cal_year_next, cal_ord_days_next = get_ordinal_date_week_date_start(
year + 1)
diff_days = cal_ord_days_next - cal_ord_days
for intervening_year in xrange(cal_year, cal_year_next):
diff_days += get_days_in_year(intervening_year)
return diff_days / CALENDAR.DAYS_IN_WEEK
def get_calendar_date_from_ordinal_date(year, day_of_year):
"""Translate an ordinal date into a calendar date.
Returns the calendar year, calendar month, calendar day-of-month.
Arguments:
year is an integer that denotes the ordinal date year
day_of_year is an integer that denotes the ordinal day in the year.
"""
iter_num_days = 0
for iter_month, iter_day in iter_months_days(year):
iter_num_days += 1
if iter_num_days == day_of_year:
return year, iter_month, iter_day
raise ValueError("Bad ordinal date: %s-%03d" % (year, day_of_year))
def get_calendar_date_from_week_date(year, week_of_year, day_of_week):
"""Translate a week date into a calendar date.
Returns the calendar year, calendar month, calendar day-of-month.
Arguments:
year is an integer that denotes the week date year (may differ
from calendar year)
week_of_year is an integer that denotes the week number in the year
day_of_week is an integer that denotes the day of the week (1-7).
"""
num_days_week_year = (
(week_of_year - 1) * CALENDAR.DAYS_IN_WEEK + day_of_week - 1)
start_year, start_month, start_day = (
get_calendar_date_week_date_start(year))
if num_days_week_year == 0:
return start_year, start_month, start_day
total_iter_days = 0
# Loop over the months and days left in the start year.
for iter_month, iter_day in iter_months_days(
start_year, month_of_year=start_month,
day_of_month=start_day + 1):
total_iter_days += 1
if num_days_week_year == total_iter_days:
return start_year, iter_month, iter_day
if start_year < year:
# We've only looped over the last year - now the current one.
for iter_month, iter_day in iter_months_days(year):
total_iter_days += 1
if num_days_week_year == total_iter_days:
return year, iter_month, iter_day
for iter_month, iter_day in iter_months_days(year + 1):
# Loop over the following year.
total_iter_days += 1
if num_days_week_year == total_iter_days:
return year + 1, iter_month, iter_day
raise ValueError("Bad week date: %s-W%02d-%s" % (year,
week_of_year,
day_of_week))
def get_ordinal_date_from_calendar_date(year, month_of_year, day_of_month):
"""Translate a calendar date into an ordinal date.
Returns the ordinal year, calendar month, calendar day-of-month.
Arguments:
year is an integer that denotes the year
month_of_year is an integer that denotes the month number in the
year.
day_of_month is an integer that denotes the day number in the
month_of_year.
"""
iter_num_days = 0
for iter_month, iter_day in iter_months_days(year):
iter_num_days += 1
if iter_month == month_of_year and iter_day == day_of_month:
return year, iter_num_days
raise ValueError("Bad calendar date: %s-%02d-%02d" % (year,
month_of_year,
day_of_month))
def get_ordinal_date_from_week_date(year, week_of_year, day_of_week):
"""Translate a week date into an ordinal date.
Returns the ordinal year, ordinal day-of-year.
Arguments:
year is an integer that denotes the week date year (which may
differ from the ordinal or calendar year)
week_of_year is an integer that denotes the week number in the
year.
day_of_week is an integer that denotes the day number in the
week_of_year.
"""
cal_year, cal_month, cal_day_of_month = get_calendar_date_from_week_date(
year, week_of_year, day_of_week)
return get_ordinal_date_from_calendar_date(
cal_year, cal_month, cal_day_of_month)
def get_week_date_from_calendar_date(year, month_of_year, day_of_month):
"""Translate a calendar date into an week date.
Returns the week date year, week-of-year, day-of-week.
Arguments:
year is an integer that denotes the calendar year, which may
differ from the week date year.
month_of_year is an integer that denotes the month number in the
above year.
day_of_month is an integer that denotes the day number in the
above month_of_year.
"""
prev_start = get_calendar_date_week_date_start(year - 1)
this_start = get_calendar_date_week_date_start(year)
next_start = get_calendar_date_week_date_start(year + 1)
cal_date = (year, month_of_year, day_of_month)
if prev_start <= cal_date < this_start:
# This calendar date is in the previous week date year.
start_year, start_month, start_day = prev_start
week_date_start_year = year - 1
elif this_start <= cal_date < next_start:
# This calendar date is in the same week date year.
start_year, start_month, start_day = this_start
week_date_start_year = year
else:
# This calendar date is in the next week date year.
start_year, start_month, start_day = next_start
week_date_start_year = year + 1
total_iter_days = -1
# A week date year can theoretically span 3 calendar years...
for iter_month, iter_day in iter_months_days(start_year,
month_of_year=start_month,
day_of_month=start_day):
total_iter_days += 1
if (start_year == year and
iter_month == month_of_year and
iter_day == day_of_month):
week_of_year = (total_iter_days / CALENDAR.DAYS_IN_WEEK) + 1
day_of_week = (total_iter_days % CALENDAR.DAYS_IN_WEEK) + 1
return week_date_start_year, week_of_year, day_of_week
for iter_start_year in [start_year + 1, start_year + 2]:
# Look at following year when the calendar date is e.g. very early Jan.
for iter_month, iter_day in iter_months_days(iter_start_year):
total_iter_days += 1
if (iter_start_year == year and
iter_month == month_of_year and
iter_day == day_of_month):
week_of_year = (total_iter_days / CALENDAR.DAYS_IN_WEEK) + 1
day_of_week = (total_iter_days % CALENDAR.DAYS_IN_WEEK) + 1
return week_date_start_year, week_of_year, day_of_week
raise ValueError("Bad calendar date: %s-%02d-%02d" % (year,
month_of_year,
day_of_month))
def get_week_date_from_ordinal_date(year, day_of_year):
"""Translate an ordinal date into a week date.
Returns the week date year, week-of-year, day-of-week.
Arguments:
year is an integer that denotes the ordinal date year, which
may differ from the week date year.
day_of_year is an integer that denotes the ordinal day in the year.
"""
year, month, day = get_calendar_date_from_ordinal_date(year, day_of_year)
return get_week_date_from_calendar_date(year, month, day)
def get_calendar_date_week_date_start(year):
"""Return the calendar date of the start of (week date) year."""
return _get_calendar_date_week_date_start(
year, calendar_mode=CALENDAR.mode)
@util.cache_results
def _get_calendar_date_week_date_start(year, calendar_mode=None):
"""Return the calendar date of the start of (week date) year."""
ref_year, ref_month, ref_day = (
CALENDAR.WEEK_DAY_START_REFERENCE["calendar"])
ref_year, ref_ordinal_day = (
CALENDAR.WEEK_DAY_START_REFERENCE["ordinal"])
if year == ref_year:
return ref_year, ref_month, ref_day
# Calculate the weekday for 1 January in this calendar year.
days_diff = 0
if year > ref_year:
days_diff = 1 - ref_ordinal_day
days_diff += get_days_in_year_range(ref_year, year - 1)
elif ref_year > year:
days_diff = ref_ordinal_day - 2
days_diff += get_days_in_year_range(year, ref_year - 1)
weekdays_diff = (days_diff) % CALENDAR.DAYS_IN_WEEK
if year > ref_year:
day_of_week_start_year = weekdays_diff + 1
else:
# Jan 1 as day of week.
day_of_week_start_year = CALENDAR.DAYS_IN_WEEK - weekdays_diff
if day_of_week_start_year == 1:
return year, 1, 1
if day_of_week_start_year > 4:
# This week belongs to the previous year; get the next Monday.
day = 1 + (8 - day_of_week_start_year)
return year, 1, day
# The week starts in the previous year - get the previous Monday.
for month, day in iter_months_days(year - 1, in_reverse=True):
day_of_week_start_year -= 1
if day_of_week_start_year == 1:
return year - 1, month, day
def get_days_since_1_ad(year):
"""Return the number of days since Jan 1, 1 A.D. to the year end."""
return _get_days_since_1_ad(year, calendar_mode=CALENDAR.mode)
@util.cache_results
def _get_days_since_1_ad(year, calendar_mode=None):
"""Return the number of days since Jan 1, 1 A.D. to the year end."""
if year == 1:
return get_days_in_year(year)
elif year < 1:
return 0
return get_days_in_year_range(1, year)
def get_ordinal_date_week_date_start(year):
"""Return the ordinal week date start for year (year, day-of-year)."""
return _get_ordinal_date_week_date_start(
year, calendar_mode=CALENDAR.mode)
@util.cache_results
def _get_ordinal_date_week_date_start(year, calendar_mode=None):
"""Return the ordinal week date start for year (year, day-of-year)."""
cal_year, cal_month, cal_day = get_calendar_date_week_date_start(year)
total_days = 0
for iter_month, iter_day in iter_months_days(cal_year):
total_days += 1
if iter_month == cal_month and iter_day == cal_day:
return cal_year, total_days
def get_timepoint_for_now():
"""Return a TimePoint at the current date/time."""
import time
return get_timepoint_from_seconds_since_unix_epoch(time.time())
def get_timepoint_from_seconds_since_unix_epoch(num_seconds):
"""Return a TimePoint at a date/time specified in Unix time.
Note that Unix time always counts 1 day = 86400 seconds, so if
we implement leap seconds we need to make the distinction.
"""
reference_timepoint = TimePoint(
**CALENDAR.UNIX_EPOCH_DATE_TIME_REFERENCE_PROPERTIES)
return reference_timepoint + Duration(seconds=float(num_seconds))
def get_timepoint_properties_from_seconds_since_unix_epoch(num_seconds):
"""Translate Unix time into a dict of TimePoint constructor properties."""
properties = dict(
get_timepoint_from_seconds_since_unix_epoch(num_seconds).get_props())
time_zone = properties.pop("time_zone")
properties["time_zone_hour"] = time_zone.hours
properties["time_zone_minute"] = time_zone.minutes
return properties
def iter_months_days(year, month_of_year=None, day_of_month=None,
in_reverse=False):
"""Iterate over each day in each month of year.
year is an integer specifying the year to use.
month_of_year is an optional integer, specifying a start month.
day_of_month is an optional integer, specifying a start day.
in_reverse is an optional boolean that reverses the iteration if
True (default False).
"""
is_leap_year = get_is_leap_year(year)
return _iter_months_days(
is_leap_year, month_of_year, day_of_month, in_reverse=in_reverse,
calendar_mode=CALENDAR.mode)
@util.cache_results
def _iter_months_days(is_leap_year, month_of_year, day_of_month,
in_reverse=False, calendar_mode=None):
source = CALENDAR.INDEXED_DAYS_IN_MONTHS
if is_leap_year:
source = CALENDAR.INDEXED_DAYS_IN_MONTHS_LEAP
if day_of_month is not None and month_of_year is None:
raise ValueError("Need to specify start month as well as day.")
results = []
if in_reverse:
if month_of_year is None:
for month_num, days in reversed(source):
day_range = range(days, 0, -1)
for day in day_range:
results.append((month_num, day))
else:
for month_num, days in reversed(source):
if month_num > month_of_year:
continue
elif month_num == month_of_year and day_of_month is not None:
day_range = range(day_of_month, 0, -1)
else:
day_range = range(days, 0, -1)
for day in day_range:
results.append((month_num, day))
else:
if month_of_year is None:
for month_num, days in source:
day_range = range(1, days + 1)
for day in day_range:
results.append((month_num, day))
else:
for month_num, days in source[month_of_year - 1:]:
if month_num == month_of_year and day_of_month is not None:
day_range = range(day_of_month, days + 1)
else:
day_range = range(1, days + 1)
for day in day_range:
results.append((month_num, day))
return results
def _int_caster(number, name="number", allow_none=False):
if allow_none and number is None:
return None
try:
int_number = int(number)
float_number = float(number)
except (TypeError, ValueError) as num_exc:
raise BadInputError(
BadInputError.INT_CAST, name, number, num_exc)
if float(int_number) != float_number:
raise BadInputError(
BadInputError.INT_REMAINDER, name, number)
return int_number
def _type_checker(*objects):
for type_info in objects:
value, name = type_info[:2]
allowed_types = list(type_info[2:])
none_is_allowed = False
if None in allowed_types:
if value is None:
break
none_is_allowed = True
allowed_types.remove(None)
allowed_types.append(type(None))
if allowed_types and isinstance(value, allowed_types[0]):
break
if int in allowed_types and float not in allowed_types:
value = _int_caster(value, name=name, allow_none=none_is_allowed)
if any(isinstance(value, type_) for type_ in allowed_types):
break
values_string = ""
if allowed_types:
values_string = " should be: "
values_string += " or ".join(
[str(v) for v in allowed_types])
raise BadInputError(
BadInputError.TYPE, name, repr(value), values_string)
PARSE_PROPERTY_TRANSLATORS = {
"seconds_since_unix_epoch":
get_timepoint_properties_from_seconds_since_unix_epoch
}
|