├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── setup.py ├── test ├── __init__.py ├── test_amud_yomi_bavli_dirshu_calculator.py ├── test_astronomical_calendar.py ├── test_daf_hashavua_bavli.py ├── test_daf_yomi_bavli_calculator.py ├── test_daf_yomi_yerushalmi_calculator.py ├── test_geo_location.py ├── test_helper.py ├── test_jewish_calendar.py ├── test_jewish_date.py ├── test_limudim_unit.py ├── test_mishna_yomis_calculator.py ├── test_noaa_calculator.py ├── test_parsha_calculator.py ├── test_pirkei_avos_calculator.py ├── test_sun_times_calculator.py ├── test_tehillim_monthly_calculator.py └── test_zmanim_calendar.py └── zmanim ├── __init__.py ├── astronomical_calendar.py ├── hebrew_calendar ├── __init__.py ├── jewish_calendar.py └── jewish_date.py ├── limudim ├── __init__.py ├── anchor.py ├── anchors │ ├── __init__.py │ ├── day_of_month_anchor.py │ └── day_of_year_anchor.py ├── calculators │ ├── __init__.py │ ├── amud_yomi_bavli_dirshu.py │ ├── daf_hashavua_bavli.py │ ├── daf_yomi_bavli.py │ ├── daf_yomi_yerushalmi.py │ ├── mishna_yomis.py │ ├── parsha.py │ ├── pirkei_avos.py │ └── tehillim_monthly.py ├── cycle.py ├── interval.py ├── limud.py ├── limud_calculator.py └── unit.py ├── util ├── __init__.py ├── astronomical_calculations.py ├── geo_location.py ├── math_helper.py ├── noaa_calculator.py └── sun_times_calculator.py └── zmanim_calendar.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | MANIFEST 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | db.sqlite3 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # Environments 85 | .env 86 | .venv 87 | env/ 88 | venv/ 89 | ENV/ 90 | env.bak/ 91 | venv.bak/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | 106 | .idea 107 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | All notable changes to this project will be documented in this file. 3 | 4 | The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) 5 | and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). 6 | 7 | ## [Unreleased] 8 | ### Added 9 | - `jewish_calendar.is_taanis_bechorim()` function added 10 | - `jewish_calendar.is_shabbos_mevorchim()` function added 11 | - `jewish_calendar.significant_shabbos()` function added 12 | - New `AmudYomiBavliDirshu` calculator for Amud Yomi Bavli following the Dirshu learning schedule 13 | - Support for limudim containing fractional units (required for Amud Yomi) 14 | 15 | ### Fixed 16 | - Bug in `jewish_date.__add__()` and `jewish_date.__sub__()` returned the base JewishDate type even when inherited. 17 | 18 | ## [0.3.1] - 2020-11-05 19 | ### Added 20 | - repr() content for limudim structures 21 | 22 | ### Fixed 23 | - Bug in `jewish_date.back()` failed when wrapping around first Jewish month 24 | 25 | ## [0.3.0] - 2020-10-13 26 | ### Added 27 | - Limudim support for: 28 | - Parsha 29 | - DafYomiBavli 30 | - DafYomiYerushalmi 31 | - DafHashavuaBavli 32 | - MishnaYomis 33 | - PirkeiAvos 34 | - TehillimMonthly 35 | - Kviah function for JewishDate 36 | - Memoization for better performance on common expensive JewishDate methods 37 | 38 | ### Fixed 39 | - Support for python-dateutil pre-2.7.0 40 | - Added Lag B'Omer as significant day / yom tov 41 | 42 | ## [0.2.1] - 2019-01-09 43 | ### Fixed 44 | - Reintroduced future annotations as quoted type 45 | - Fixed bug on optimization branch for large increments/decrements 46 | 47 | ## [0.2.0] - 2018-10-04 48 | ### Added 49 | - Backward support for Python 3.6 (removed future annotations) 50 | 51 | ## [0.1.0] - 2018-09-17 52 | ### Added 53 | - Elevations used in shaos zmanios calculations if use_elevation property is set 54 | - Hanetz and Shkia methods will use the appropriate calculation based on use_elevation setting 55 | - Support Alos and Tzais offset using temporal minutes 56 | - Various Assur Bemelacha related methods for calendar dates using JewishCalendar, 57 | as well as point-in-time using ZmanimCalendar. 58 | - Delayed candle lighting 59 | 60 | ## [0.0.2] - 2018-08-27 61 | ### Added 62 | - README examples 63 | - repr() content for standard classes 64 | - This changelog :) 65 | 66 | ### Fixed 67 | - Package license to reflect LGPLv2.1 68 | - hebrew_calendar module now included in the package 69 | - package includes required dependencies and python version 70 | 71 | ## [0.0.1] - 2018-08-24 72 | ### Original Alpha Release 73 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 2.1, February 1999 3 | 4 | Copyright (C) 1991, 1999 Free Software Foundation, Inc. 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | [This is the first released version of the Lesser GPL. It also counts 10 | as the successor of the GNU Library Public License, version 2, hence 11 | the version number 2.1.] 12 | 13 | Preamble 14 | 15 | The licenses for most software are designed to take away your 16 | freedom to share and change it. By contrast, the GNU General Public 17 | Licenses are intended to guarantee your freedom to share and change 18 | free software--to make sure the software is free for all its users. 19 | 20 | This license, the Lesser General Public License, applies to some 21 | specially designated software packages--typically libraries--of the 22 | Free Software Foundation and other authors who decide to use it. You 23 | can use it too, but we suggest you first think carefully about whether 24 | this license or the ordinary General Public License is the better 25 | strategy to use in any particular case, based on the explanations below. 26 | 27 | When we speak of free software, we are referring to freedom of use, 28 | not price. Our General Public Licenses are designed to make sure that 29 | you have the freedom to distribute copies of free software (and charge 30 | for this service if you wish); that you receive source code or can get 31 | it if you want it; that you can change the software and use pieces of 32 | it in new free programs; and that you are informed that you can do 33 | these things. 34 | 35 | To protect your rights, we need to make restrictions that forbid 36 | distributors to deny you these rights or to ask you to surrender these 37 | rights. These restrictions translate to certain responsibilities for 38 | you if you distribute copies of the library or if you modify it. 39 | 40 | For example, if you distribute copies of the library, whether gratis 41 | or for a fee, you must give the recipients all the rights that we gave 42 | you. You must make sure that they, too, receive or can get the source 43 | code. If you link other code with the library, you must provide 44 | complete object files to the recipients, so that they can relink them 45 | with the library after making changes to the library and recompiling 46 | it. And you must show them these terms so they know their rights. 47 | 48 | We protect your rights with a two-step method: (1) we copyright the 49 | library, and (2) we offer you this license, which gives you legal 50 | permission to copy, distribute and/or modify the library. 51 | 52 | To protect each distributor, we want to make it very clear that 53 | there is no warranty for the free library. Also, if the library is 54 | modified by someone else and passed on, the recipients should know 55 | that what they have is not the original version, so that the original 56 | author's reputation will not be affected by problems that might be 57 | introduced by others. 58 | 59 | Finally, software patents pose a constant threat to the existence of 60 | any free program. We wish to make sure that a company cannot 61 | effectively restrict the users of a free program by obtaining a 62 | restrictive license from a patent holder. Therefore, we insist that 63 | any patent license obtained for a version of the library must be 64 | consistent with the full freedom of use specified in this license. 65 | 66 | Most GNU software, including some libraries, is covered by the 67 | ordinary GNU General Public License. This license, the GNU Lesser 68 | General Public License, applies to certain designated libraries, and 69 | is quite different from the ordinary General Public License. We use 70 | this license for certain libraries in order to permit linking those 71 | libraries into non-free programs. 72 | 73 | When a program is linked with a library, whether statically or using 74 | a shared library, the combination of the two is legally speaking a 75 | combined work, a derivative of the original library. The ordinary 76 | General Public License therefore permits such linking only if the 77 | entire combination fits its criteria of freedom. The Lesser General 78 | Public License permits more lax criteria for linking other code with 79 | the library. 80 | 81 | We call this license the "Lesser" General Public License because it 82 | does Less to protect the user's freedom than the ordinary General 83 | Public License. It also provides other free software developers Less 84 | of an advantage over competing non-free programs. These disadvantages 85 | are the reason we use the ordinary General Public License for many 86 | libraries. However, the Lesser license provides advantages in certain 87 | special circumstances. 88 | 89 | For example, on rare occasions, there may be a special need to 90 | encourage the widest possible use of a certain library, so that it becomes 91 | a de-facto standard. To achieve this, non-free programs must be 92 | allowed to use the library. A more frequent case is that a free 93 | library does the same job as widely used non-free libraries. In this 94 | case, there is little to gain by limiting the free library to free 95 | software only, so we use the Lesser General Public License. 96 | 97 | In other cases, permission to use a particular library in non-free 98 | programs enables a greater number of people to use a large body of 99 | free software. For example, permission to use the GNU C Library in 100 | non-free programs enables many more people to use the whole GNU 101 | operating system, as well as its variant, the GNU/Linux operating 102 | system. 103 | 104 | Although the Lesser General Public License is Less protective of the 105 | users' freedom, it does ensure that the user of a program that is 106 | linked with the Library has the freedom and the wherewithal to run 107 | that program using a modified version of the Library. 108 | 109 | The precise terms and conditions for copying, distribution and 110 | modification follow. Pay close attention to the difference between a 111 | "work based on the library" and a "work that uses the library". The 112 | former contains code derived from the library, whereas the latter must 113 | be combined with the library in order to run. 114 | 115 | GNU LESSER GENERAL PUBLIC LICENSE 116 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 117 | 118 | 0. This License Agreement applies to any software library or other 119 | program which contains a notice placed by the copyright holder or 120 | other authorized party saying it may be distributed under the terms of 121 | this Lesser General Public License (also called "this License"). 122 | Each licensee is addressed as "you". 123 | 124 | A "library" means a collection of software functions and/or data 125 | prepared so as to be conveniently linked with application programs 126 | (which use some of those functions and data) to form executables. 127 | 128 | The "Library", below, refers to any such software library or work 129 | which has been distributed under these terms. A "work based on the 130 | Library" means either the Library or any derivative work under 131 | copyright law: that is to say, a work containing the Library or a 132 | portion of it, either verbatim or with modifications and/or translated 133 | straightforwardly into another language. (Hereinafter, translation is 134 | included without limitation in the term "modification".) 135 | 136 | "Source code" for a work means the preferred form of the work for 137 | making modifications to it. For a library, complete source code means 138 | all the source code for all modules it contains, plus any associated 139 | interface definition files, plus the scripts used to control compilation 140 | and installation of the library. 141 | 142 | Activities other than copying, distribution and modification are not 143 | covered by this License; they are outside its scope. The act of 144 | running a program using the Library is not restricted, and output from 145 | such a program is covered only if its contents constitute a work based 146 | on the Library (independent of the use of the Library in a tool for 147 | writing it). Whether that is true depends on what the Library does 148 | and what the program that uses the Library does. 149 | 150 | 1. You may copy and distribute verbatim copies of the Library's 151 | complete source code as you receive it, in any medium, provided that 152 | you conspicuously and appropriately publish on each copy an 153 | appropriate copyright notice and disclaimer of warranty; keep intact 154 | all the notices that refer to this License and to the absence of any 155 | warranty; and distribute a copy of this License along with the 156 | Library. 157 | 158 | You may charge a fee for the physical act of transferring a copy, 159 | and you may at your option offer warranty protection in exchange for a 160 | fee. 161 | 162 | 2. You may modify your copy or copies of the Library or any portion 163 | of it, thus forming a work based on the Library, and copy and 164 | distribute such modifications or work under the terms of Section 1 165 | above, provided that you also meet all of these conditions: 166 | 167 | a) The modified work must itself be a software library. 168 | 169 | b) You must cause the files modified to carry prominent notices 170 | stating that you changed the files and the date of any change. 171 | 172 | c) You must cause the whole of the work to be licensed at no 173 | charge to all third parties under the terms of this License. 174 | 175 | d) If a facility in the modified Library refers to a function or a 176 | table of data to be supplied by an application program that uses 177 | the facility, other than as an argument passed when the facility 178 | is invoked, then you must make a good faith effort to ensure that, 179 | in the event an application does not supply such function or 180 | table, the facility still operates, and performs whatever part of 181 | its purpose remains meaningful. 182 | 183 | (For example, a function in a library to compute square roots has 184 | a purpose that is entirely well-defined independent of the 185 | application. Therefore, Subsection 2d requires that any 186 | application-supplied function or table used by this function must 187 | be optional: if the application does not supply it, the square 188 | root function must still compute square roots.) 189 | 190 | These requirements apply to the modified work as a whole. If 191 | identifiable sections of that work are not derived from the Library, 192 | and can be reasonably considered independent and separate works in 193 | themselves, then this License, and its terms, do not apply to those 194 | sections when you distribute them as separate works. But when you 195 | distribute the same sections as part of a whole which is a work based 196 | on the Library, the distribution of the whole must be on the terms of 197 | this License, whose permissions for other licensees extend to the 198 | entire whole, and thus to each and every part regardless of who wrote 199 | it. 200 | 201 | Thus, it is not the intent of this section to claim rights or contest 202 | your rights to work written entirely by you; rather, the intent is to 203 | exercise the right to control the distribution of derivative or 204 | collective works based on the Library. 205 | 206 | In addition, mere aggregation of another work not based on the Library 207 | with the Library (or with a work based on the Library) on a volume of 208 | a storage or distribution medium does not bring the other work under 209 | the scope of this License. 210 | 211 | 3. You may opt to apply the terms of the ordinary GNU General Public 212 | License instead of this License to a given copy of the Library. To do 213 | this, you must alter all the notices that refer to this License, so 214 | that they refer to the ordinary GNU General Public License, version 2, 215 | instead of to this License. (If a newer version than version 2 of the 216 | ordinary GNU General Public License has appeared, then you can specify 217 | that version instead if you wish.) Do not make any other change in 218 | these notices. 219 | 220 | Once this change is made in a given copy, it is irreversible for 221 | that copy, so the ordinary GNU General Public License applies to all 222 | subsequent copies and derivative works made from that copy. 223 | 224 | This option is useful when you wish to copy part of the code of 225 | the Library into a program that is not a library. 226 | 227 | 4. You may copy and distribute the Library (or a portion or 228 | derivative of it, under Section 2) in object code or executable form 229 | under the terms of Sections 1 and 2 above provided that you accompany 230 | it with the complete corresponding machine-readable source code, which 231 | must be distributed under the terms of Sections 1 and 2 above on a 232 | medium customarily used for software interchange. 233 | 234 | If distribution of object code is made by offering access to copy 235 | from a designated place, then offering equivalent access to copy the 236 | source code from the same place satisfies the requirement to 237 | distribute the source code, even though third parties are not 238 | compelled to copy the source along with the object code. 239 | 240 | 5. A program that contains no derivative of any portion of the 241 | Library, but is designed to work with the Library by being compiled or 242 | linked with it, is called a "work that uses the Library". Such a 243 | work, in isolation, is not a derivative work of the Library, and 244 | therefore falls outside the scope of this License. 245 | 246 | However, linking a "work that uses the Library" with the Library 247 | creates an executable that is a derivative of the Library (because it 248 | contains portions of the Library), rather than a "work that uses the 249 | library". The executable is therefore covered by this License. 250 | Section 6 states terms for distribution of such executables. 251 | 252 | When a "work that uses the Library" uses material from a header file 253 | that is part of the Library, the object code for the work may be a 254 | derivative work of the Library even though the source code is not. 255 | Whether this is true is especially significant if the work can be 256 | linked without the Library, or if the work is itself a library. The 257 | threshold for this to be true is not precisely defined by law. 258 | 259 | If such an object file uses only numerical parameters, data 260 | structure layouts and accessors, and small macros and small inline 261 | functions (ten lines or less in length), then the use of the object 262 | file is unrestricted, regardless of whether it is legally a derivative 263 | work. (Executables containing this object code plus portions of the 264 | Library will still fall under Section 6.) 265 | 266 | Otherwise, if the work is a derivative of the Library, you may 267 | distribute the object code for the work under the terms of Section 6. 268 | Any executables containing that work also fall under Section 6, 269 | whether or not they are linked directly with the Library itself. 270 | 271 | 6. As an exception to the Sections above, you may also combine or 272 | link a "work that uses the Library" with the Library to produce a 273 | work containing portions of the Library, and distribute that work 274 | under terms of your choice, provided that the terms permit 275 | modification of the work for the customer's own use and reverse 276 | engineering for debugging such modifications. 277 | 278 | You must give prominent notice with each copy of the work that the 279 | Library is used in it and that the Library and its use are covered by 280 | this License. You must supply a copy of this License. If the work 281 | during execution displays copyright notices, you must include the 282 | copyright notice for the Library among them, as well as a reference 283 | directing the user to the copy of this License. Also, you must do one 284 | of these things: 285 | 286 | a) Accompany the work with the complete corresponding 287 | machine-readable source code for the Library including whatever 288 | changes were used in the work (which must be distributed under 289 | Sections 1 and 2 above); and, if the work is an executable linked 290 | with the Library, with the complete machine-readable "work that 291 | uses the Library", as object code and/or source code, so that the 292 | user can modify the Library and then relink to produce a modified 293 | executable containing the modified Library. (It is understood 294 | that the user who changes the contents of definitions files in the 295 | Library will not necessarily be able to recompile the application 296 | to use the modified definitions.) 297 | 298 | b) Use a suitable shared library mechanism for linking with the 299 | Library. A suitable mechanism is one that (1) uses at run time a 300 | copy of the library already present on the user's computer system, 301 | rather than copying library functions into the executable, and (2) 302 | will operate properly with a modified version of the library, if 303 | the user installs one, as long as the modified version is 304 | interface-compatible with the version that the work was made with. 305 | 306 | c) Accompany the work with a written offer, valid for at 307 | least three years, to give the same user the materials 308 | specified in Subsection 6a, above, for a charge no more 309 | than the cost of performing this distribution. 310 | 311 | d) If distribution of the work is made by offering access to copy 312 | from a designated place, offer equivalent access to copy the above 313 | specified materials from the same place. 314 | 315 | e) Verify that the user has already received a copy of these 316 | materials or that you have already sent this user a copy. 317 | 318 | For an executable, the required form of the "work that uses the 319 | Library" must include any data and utility programs needed for 320 | reproducing the executable from it. However, as a special exception, 321 | the materials to be distributed need not include anything that is 322 | normally distributed (in either source or binary form) with the major 323 | components (compiler, kernel, and so on) of the operating system on 324 | which the executable runs, unless that component itself accompanies 325 | the executable. 326 | 327 | It may happen that this requirement contradicts the license 328 | restrictions of other proprietary libraries that do not normally 329 | accompany the operating system. Such a contradiction means you cannot 330 | use both them and the Library together in an executable that you 331 | distribute. 332 | 333 | 7. You may place library facilities that are a work based on the 334 | Library side-by-side in a single library together with other library 335 | facilities not covered by this License, and distribute such a combined 336 | library, provided that the separate distribution of the work based on 337 | the Library and of the other library facilities is otherwise 338 | permitted, and provided that you do these two things: 339 | 340 | a) Accompany the combined library with a copy of the same work 341 | based on the Library, uncombined with any other library 342 | facilities. This must be distributed under the terms of the 343 | Sections above. 344 | 345 | b) Give prominent notice with the combined library of the fact 346 | that part of it is a work based on the Library, and explaining 347 | where to find the accompanying uncombined form of the same work. 348 | 349 | 8. You may not copy, modify, sublicense, link with, or distribute 350 | the Library except as expressly provided under this License. Any 351 | attempt otherwise to copy, modify, sublicense, link with, or 352 | distribute the Library is void, and will automatically terminate your 353 | rights under this License. However, parties who have received copies, 354 | or rights, from you under this License will not have their licenses 355 | terminated so long as such parties remain in full compliance. 356 | 357 | 9. You are not required to accept this License, since you have not 358 | signed it. However, nothing else grants you permission to modify or 359 | distribute the Library or its derivative works. These actions are 360 | prohibited by law if you do not accept this License. Therefore, by 361 | modifying or distributing the Library (or any work based on the 362 | Library), you indicate your acceptance of this License to do so, and 363 | all its terms and conditions for copying, distributing or modifying 364 | the Library or works based on it. 365 | 366 | 10. Each time you redistribute the Library (or any work based on the 367 | Library), the recipient automatically receives a license from the 368 | original licensor to copy, distribute, link with or modify the Library 369 | subject to these terms and conditions. You may not impose any further 370 | restrictions on the recipients' exercise of the rights granted herein. 371 | You are not responsible for enforcing compliance by third parties with 372 | this License. 373 | 374 | 11. If, as a consequence of a court judgment or allegation of patent 375 | infringement or for any other reason (not limited to patent issues), 376 | conditions are imposed on you (whether by court order, agreement or 377 | otherwise) that contradict the conditions of this License, they do not 378 | excuse you from the conditions of this License. If you cannot 379 | distribute so as to satisfy simultaneously your obligations under this 380 | License and any other pertinent obligations, then as a consequence you 381 | may not distribute the Library at all. For example, if a patent 382 | license would not permit royalty-free redistribution of the Library by 383 | all those who receive copies directly or indirectly through you, then 384 | the only way you could satisfy both it and this License would be to 385 | refrain entirely from distribution of the Library. 386 | 387 | If any portion of this section is held invalid or unenforceable under any 388 | particular circumstance, the balance of the section is intended to apply, 389 | and the section as a whole is intended to apply in other circumstances. 390 | 391 | It is not the purpose of this section to induce you to infringe any 392 | patents or other property right claims or to contest validity of any 393 | such claims; this section has the sole purpose of protecting the 394 | integrity of the free software distribution system which is 395 | implemented by public license practices. Many people have made 396 | generous contributions to the wide range of software distributed 397 | through that system in reliance on consistent application of that 398 | system; it is up to the author/donor to decide if he or she is willing 399 | to distribute software through any other system and a licensee cannot 400 | impose that choice. 401 | 402 | This section is intended to make thoroughly clear what is believed to 403 | be a consequence of the rest of this License. 404 | 405 | 12. If the distribution and/or use of the Library is restricted in 406 | certain countries either by patents or by copyrighted interfaces, the 407 | original copyright holder who places the Library under this License may add 408 | an explicit geographical distribution limitation excluding those countries, 409 | so that distribution is permitted only in or among countries not thus 410 | excluded. In such case, this License incorporates the limitation as if 411 | written in the body of this License. 412 | 413 | 13. The Free Software Foundation may publish revised and/or new 414 | versions of the Lesser General Public License from time to time. 415 | Such new versions will be similar in spirit to the present version, 416 | but may differ in detail to address new problems or concerns. 417 | 418 | Each version is given a distinguishing version number. If the Library 419 | specifies a version number of this License which applies to it and 420 | "any later version", you have the option of following the terms and 421 | conditions either of that version or of any later version published by 422 | the Free Software Foundation. If the Library does not specify a 423 | license version number, you may choose any version ever published by 424 | the Free Software Foundation. 425 | 426 | 14. If you wish to incorporate parts of the Library into other free 427 | programs whose distribution conditions are incompatible with these, 428 | write to the author to ask for permission. For software which is 429 | copyrighted by the Free Software Foundation, write to the Free 430 | Software Foundation; we sometimes make exceptions for this. Our 431 | decision will be guided by the two goals of preserving the free status 432 | of all derivatives of our free software and of promoting the sharing 433 | and reuse of software generally. 434 | 435 | NO WARRANTY 436 | 437 | 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO 438 | WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. 439 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR 440 | OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY 441 | KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE 442 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 443 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE 444 | LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME 445 | THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 446 | 447 | 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN 448 | WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY 449 | AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU 450 | FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR 451 | CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE 452 | LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING 453 | RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A 454 | FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF 455 | SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 456 | DAMAGES. 457 | 458 | END OF TERMS AND CONDITIONS 459 | 460 | How to Apply These Terms to Your New Libraries 461 | 462 | If you develop a new library, and you want it to be of the greatest 463 | possible use to the public, we recommend making it free software that 464 | everyone can redistribute and change. You can do so by permitting 465 | redistribution under these terms (or, alternatively, under the terms of the 466 | ordinary General Public License). 467 | 468 | To apply these terms, attach the following notices to the library. It is 469 | safest to attach them to the start of each source file to most effectively 470 | convey the exclusion of warranty; and each file should have at least the 471 | "copyright" line and a pointer to where the full notice is found. 472 | 473 | 474 | Copyright (C) 475 | 476 | This library is free software; you can redistribute it and/or 477 | modify it under the terms of the GNU Lesser General Public 478 | License as published by the Free Software Foundation; either 479 | version 2.1 of the License, or (at your option) any later version. 480 | 481 | This library is distributed in the hope that it will be useful, 482 | but WITHOUT ANY WARRANTY; without even the implied warranty of 483 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 484 | Lesser General Public License for more details. 485 | 486 | You should have received a copy of the GNU Lesser General Public 487 | License along with this library; if not, write to the Free Software 488 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 489 | USA 490 | 491 | Also add information on how to contact you by electronic and paper mail. 492 | 493 | You should also get your employer (if you work as a programmer) or your 494 | school, if any, to sign a "copyright disclaimer" for the library, if 495 | necessary. Here is a sample; alter the names: 496 | 497 | Yoyodyne, Inc., hereby disclaims all copyright interest in the 498 | library `Frob' (a library for tweaking knobs) written by James Random 499 | Hacker. 500 | 501 | , 1 April 1990 502 | Ty Coon, President of Vice 503 | 504 | That's all there is to it! 505 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # python-zmanim 2 | Python Zmanim library 3 | 4 | This project is a port from Eliyahu Hershfeld's [KosherJava project](https://github.com/KosherJava/zmanim), with some Python niceties and other minor modifications. 5 | 6 | ## Usage 7 | 8 | Some common examples include... 9 | 10 | #### Zmanim calculations 11 | 12 | ```python 13 | # Initialize a new ZmanimCalendar object, defaults to using today's date in GMT, located at Greenwich, England 14 | from zmanim.zmanim_calendar import ZmanimCalendar 15 | calendar = ZmanimCalendar() 16 | calendar 17 | #=> zmanim.zmanim_calendar.ZmanimCalendar(candle_lighting_offset=18, geo_location=zmanim.util.geo_location.GeoLocation(name='Greenwich, England', latitude=51.4772, longitude=0.0, time_zone=tzfile('/usr/share/zoneinfo/GMT'), elevation=0.0), date=datetime.datetime(2018, 8, 26, 11, 40, 29, 334774), calculator=) 18 | 19 | # Calculate the sunset for today at that location 20 | calendar.sunset() 21 | #=> datetime.datetime(2018, 8, 26, 18, 58, 40, 796469, tzinfo=tzfile('/usr/share/zoneinfo/GMT')) 22 | 23 | # Prepare a new location 24 | from zmanim.util.geo_location import GeoLocation 25 | location = GeoLocation('Lakewood, NJ', 40.0721087, -74.2400243, 'America/New_York', elevation=15) 26 | location 27 | #=> zmanim.util.geo_location.GeoLocation(name='Lakewood, NJ', latitude=40.0721087, longitude=-74.2400243, time_zone=tzfile('/usr/share/zoneinfo/America/New_York'), elevation=15.0) 28 | 29 | # Initialize a new ZmanimCalendar object, passing a specific location and date 30 | from datetime import date 31 | calendar = ZmanimCalendar(geo_location=location, date=date(2017, 12, 15)) 32 | calendar 33 | #=> zmanim.zmanim_calendar.ZmanimCalendar(candle_lighting_offset=18, geo_location=zmanim.util.geo_location.GeoLocation(name='Lakewood, NJ', latitude=40.0721087, longitude=-74.2400243, time_zone=tzfile('/usr/share/zoneinfo/America/New_York'), elevation=15.0), date=datetime.date(2017, 12, 15), calculator=) 34 | 35 | # Calculate Sof Zman Krias Shma for that location/date per the opinion of GR"A 36 | calendar.sof_zman_shma_gra() 37 | #=> datetime.datetime(2017, 12, 15, 9, 32, 9, 383390, tzinfo=tzfile('/usr/share/zoneinfo/America/New_York')) 38 | ``` 39 | 40 | #### Date Calculations 41 | 42 | ```python 43 | # Initialize a new JewishDate object with today's date 44 | from zmanim.hebrew_calendar.jewish_date import JewishDate 45 | date = JewishDate() 46 | date 47 | #=> 48 | 49 | # Calculate the JewishDate from 25 days ago 50 | date - 25 51 | #=> 52 | 53 | # Initialize a new JewishCalendar object for Pesach of this Jewish calendar year 54 | from zmanim.hebrew_calendar.jewish_calendar import JewishCalendar 55 | pesach = JewishCalendar(date.jewish_year, 1, 15) 56 | pesach 57 | #=> 58 | pesach.significant_day() 59 | #=> 'pesach' 60 | pesach.is_yom_tov_assur_bemelacha() 61 | #=> True 62 | ``` 63 | 64 | There is much more functionality included than demonstrated here. Feel free to experiment or read the source code to learn more! 65 | 66 | --- 67 | ## Contributing 68 | 69 | Bug reports and pull requests are welcome on GitHub at https://github.com/pinnymz/python-zmanim. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct. 70 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import setuptools 2 | 3 | with open("README.md", "r") as fh: 4 | long_description = fh.read() 5 | 6 | setuptools.setup( 7 | name="zmanim", 8 | version="0.3.1", 9 | author="Pinny Markowitz", 10 | author_email="pinny@mwitz.com", 11 | description="A Zmanim library for Python", 12 | long_description=long_description, 13 | long_description_content_type="text/markdown", 14 | url="https://github.com/pinnymz/python-zmanim", 15 | packages=setuptools.find_packages(exclude=['test']), 16 | classifiers=[ 17 | "Programming Language :: Python :: 3", 18 | "Programming Language :: Python :: 3.6", 19 | "Programming Language :: Python :: 3.7", 20 | "Programming Language :: Python :: 3.8", 21 | "License :: OSI Approved :: GNU Lesser General Public License v2 or later (LGPLv2+)", 22 | "Operating System :: OS Independent", 23 | ], 24 | install_requires=['python-dateutil', 'julian', 'memoization'], 25 | python_requires='>=3.6' 26 | ) -------------------------------------------------------------------------------- /test/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pinnymz/python-zmanim/d33b8fe499de36a696e07662197a76ebcb5ee89e/test/__init__.py -------------------------------------------------------------------------------- /test/test_amud_yomi_bavli_dirshu_calculator.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from datetime import date 3 | 4 | from zmanim.limudim.calculators.amud_yomi_bavli_dirshu import AmudYomiBavliDirshu 5 | 6 | 7 | class TestAmudYomiBavliDirshuCalculator(unittest.TestCase): 8 | def test_simple_date(self): 9 | test_date = date(2024, 5, 30) 10 | limud = AmudYomiBavliDirshu().limud(test_date) 11 | self.assertEqual(limud.start_date(), test_date) 12 | self.assertEqual(limud.end_date(), test_date) 13 | self.assertEqual(limud.description(), 'shabbos 53a') 14 | 15 | def test_before_cycle_began(self): 16 | test_date = date(2023, 1, 1) 17 | limud = AmudYomiBavliDirshu().limud(test_date) 18 | self.assertIsNone(limud) 19 | 20 | def test_first_day_of_cycle(self): 21 | test_date = date(2038, 8, 4) 22 | limud = AmudYomiBavliDirshu().limud(test_date) 23 | self.assertEqual(limud.start_date(), test_date) 24 | self.assertEqual(limud.end_date(), test_date) 25 | self.assertEqual(limud.description(), 'berachos 2a') 26 | 27 | def test_last_day_of_cycle(self): 28 | test_date = date(2038, 8, 3) 29 | limud = AmudYomiBavliDirshu().limud(test_date) 30 | self.assertEqual(limud.description(), 'niddah 73a') 31 | 32 | def test_end_of_meilah(self): 33 | test_date = date(2038, 2, 10) 34 | limud = AmudYomiBavliDirshu().limud(test_date) 35 | self.assertEqual(limud.description(), 'meilah 22a') 36 | 37 | def test_beginning_of_kinnim(self): 38 | test_date = date(2038, 2, 11) 39 | limud = AmudYomiBavliDirshu().limud(test_date) 40 | self.assertEqual(limud.description(), 'kinnim 22b') 41 | 42 | def test_end_of_kinnim(self): 43 | test_date = date(2038, 2, 16) 44 | limud = AmudYomiBavliDirshu().limud(test_date) 45 | self.assertEqual(limud.description(), 'kinnim 25a') 46 | 47 | def test_beginning_of_tamid(self): 48 | test_date = date(2038, 2, 17) 49 | limud = AmudYomiBavliDirshu().limud(test_date) 50 | self.assertEqual(limud.description(), 'tamid 25b') 51 | 52 | def test_end_of_tamid(self): 53 | test_date = date(2038, 3, 5) 54 | limud = AmudYomiBavliDirshu().limud(test_date) 55 | self.assertEqual(limud.description(), 'tamid 33b') 56 | 57 | def test_beginning_of_midos(self): 58 | test_date = date(2038, 3, 6) 59 | limud = AmudYomiBavliDirshu().limud(test_date) 60 | self.assertEqual(limud.description(), 'midos 34a') 61 | 62 | def test_end_of_midos(self): 63 | test_date = date(2038, 3, 13) 64 | limud = AmudYomiBavliDirshu().limud(test_date) 65 | self.assertEqual(limud.description(), 'midos 37b') 66 | 67 | def test_after_midos(self): 68 | test_date = date(2038, 3, 14) 69 | limud = AmudYomiBavliDirshu().limud(test_date) 70 | self.assertEqual(limud.description(), 'niddah 2a') 71 | -------------------------------------------------------------------------------- /test/test_astronomical_calendar.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from datetime import date 3 | 4 | from test import test_helper 5 | from zmanim.astronomical_calendar import AstronomicalCalendar 6 | from zmanim.util.math_helper import MathHelper 7 | 8 | 9 | class TestAstronomicalCalendar(unittest.TestCase): 10 | def test_sunrise(self): 11 | expected_dates = ["2017-10-17T07:09:11-04:00", 12 | "2017-10-17T06:39:32+03:00", 13 | "2017-10-17T07:00:25-07:00", 14 | "2017-10-17T05:48:20+09:00", 15 | None, 16 | "2017-10-17T06:54:18+14:00"] 17 | expected = zip(test_helper.basic_locations(), expected_dates) 18 | calc = AstronomicalCalendar(date=date(2017, 10, 17)) 19 | 20 | def test_entry(geo): 21 | calc.geo_location = geo 22 | result = calc.sunrise() 23 | return geo, (None if result is None else result.replace(microsecond=0).isoformat()) 24 | 25 | for entry in expected: 26 | self.assertEqual(test_entry(entry[0]), entry) 27 | 28 | def test_sunset(self): 29 | expected_dates = ["2017-10-17T18:14:38-04:00", 30 | "2017-10-17T18:08:46+03:00", 31 | "2017-10-17T18:19:05-07:00", 32 | "2017-10-17T17:04:46+09:00", 33 | None, 34 | "2017-10-17T19:31:07+14:00"] 35 | expected = zip(test_helper.basic_locations(), expected_dates) 36 | calc = AstronomicalCalendar(date=date(2017, 10, 17)) 37 | 38 | def test_entry(geo): 39 | calc.geo_location = geo 40 | result = calc.sunset() 41 | return geo, (None if result is None else result.replace(microsecond=0).isoformat()) 42 | 43 | for entry in expected: 44 | self.assertEqual(test_entry(entry[0]), entry) 45 | 46 | def test_sea_level_sunrise(self): 47 | expected_dates = ["2017-10-17T07:09:51-04:00", 48 | "2017-10-17T06:43:43+03:00", 49 | "2017-10-17T07:01:45-07:00", 50 | "2017-10-17T05:49:21+09:00", 51 | None, 52 | "2017-10-17T07:00:05+14:00"] 53 | expected = zip(test_helper.basic_locations(), expected_dates) 54 | calc = AstronomicalCalendar(date=date(2017, 10, 17)) 55 | 56 | def test_entry(geo): 57 | calc.geo_location = geo 58 | result = calc.sea_level_sunrise() 59 | return geo, (None if result is None else result.replace(microsecond=0).isoformat()) 60 | 61 | for entry in expected: 62 | self.assertEqual(test_entry(entry[0]), entry) 63 | 64 | def test_sea_level_sunset(self): 65 | expected_dates = ["2017-10-17T18:13:58-04:00", 66 | "2017-10-17T18:04:36+03:00", 67 | "2017-10-17T18:17:45-07:00", 68 | "2017-10-17T17:03:45+09:00", 69 | None, 70 | "2017-10-17T19:25:19+14:00"] 71 | expected = zip(test_helper.basic_locations(), expected_dates) 72 | calc = AstronomicalCalendar(date=date(2017, 10, 17)) 73 | 74 | def test_entry(geo): 75 | calc.geo_location = geo 76 | result = calc.sea_level_sunset() 77 | return geo, (None if result is None else result.replace(microsecond=0).isoformat()) 78 | 79 | for entry in expected: 80 | self.assertEqual(test_entry(entry[0]), entry) 81 | 82 | def test_utc_sunrise(self): 83 | expected_times = [11.15327065, 3.65893934, 14.00708152, 20.8057012, None, 16.90510688] 84 | expected = zip(test_helper.basic_locations(), expected_times) 85 | calc = AstronomicalCalendar(date=date(2017, 10, 17)) 86 | 87 | def test_entry(geo): 88 | calc.geo_location = geo 89 | result = calc.utc_sunrise(90) 90 | return geo, (None if result is None else round(result, 8)) 91 | 92 | for entry in expected: 93 | self.assertEqual(test_entry(entry[0]), entry) 94 | 95 | def test_utc_sunset(self): 96 | expected_times = [22.24410903, 15.14635336, 1.31819979, 8.07962871, None, 5.51873532] 97 | expected = zip(test_helper.basic_locations(), expected_times) 98 | calc = AstronomicalCalendar(date=date(2017, 10, 17)) 99 | 100 | def test_entry(geo): 101 | calc.geo_location = geo 102 | result = calc.utc_sunset(90) 103 | return geo, (None if result is None else round(result, 8)) 104 | 105 | for entry in expected: 106 | self.assertEqual(test_entry(entry[0]), entry) 107 | 108 | def test_utc_sea_level_sunrise(self): 109 | expected_times = [11.16434723, 3.72862262, 14.02926518, 20.82268461, None, 17.00158411] 110 | expected = zip(test_helper.basic_locations(), expected_times) 111 | calc = AstronomicalCalendar(date=date(2017, 10, 17)) 112 | 113 | def test_entry(geo): 114 | calc.geo_location = geo 115 | result = calc.utc_sea_level_sunrise(90) 116 | return geo, (None if result is None else round(result, 8)) 117 | 118 | for entry in expected: 119 | self.assertEqual(test_entry(entry[0]), entry) 120 | 121 | def test_utc_sea_level_sunset(self): 122 | expected_times = [22.23304301, 15.07671429, 1.29603174, 8.06265871, None, 5.42214918] 123 | expected = zip(test_helper.basic_locations(), expected_times) 124 | calc = AstronomicalCalendar(date=date(2017, 10, 17)) 125 | 126 | def test_entry(geo): 127 | calc.geo_location = geo 128 | result = calc.utc_sea_level_sunset(90) 129 | return geo, (None if result is None else round(result, 8)) 130 | 131 | for entry in expected: 132 | self.assertEqual(test_entry(entry[0]), entry) 133 | 134 | def test_sunrise_offset_by_degrees_for_basic_locations(self): 135 | expected_dates = ["2017-10-17T06:10:57-04:00", 136 | "2017-10-17T05:50:43+03:00", 137 | "2017-10-17T06:07:22-07:00", 138 | "2017-10-17T04:53:55+09:00", 139 | "2017-10-17T04:47:28-04:00", 140 | "2017-10-17T06:13:13+14:00"] 141 | expected = zip(test_helper.basic_locations(), expected_dates) 142 | calc = AstronomicalCalendar(date=date(2017, 10, 17)) 143 | 144 | def test_entry(geo): 145 | calc.geo_location = geo 146 | result = calc.sunrise_offset_by_degrees(102) 147 | return geo, (None if result is None else result.replace(microsecond=0).isoformat()) 148 | 149 | for entry in expected: 150 | self.assertEqual(test_entry(entry[0]), entry) 151 | 152 | def test_sunrise_offset_by_degrees_for_arctic_timezone_extremities(self): 153 | calc = AstronomicalCalendar(date=date(2017, 4, 20)) 154 | calc.geo_location = test_helper.daneborg() 155 | result = calc.sunrise_offset_by_degrees(94) 156 | self.assertEqual(result.replace(microsecond=0).isoformat(), "2017-04-19T23:54:23-02:00") 157 | 158 | def test_sunset_offset_by_degrees_for_basic_locations(self): 159 | expected_dates = ["2017-10-17T19:12:49-04:00", 160 | "2017-10-17T18:57:33+03:00", 161 | "2017-10-17T19:12:05-07:00", 162 | "2017-10-17T17:59:08+09:00", 163 | "2017-10-17T19:15:04-04:00", 164 | "2017-10-17T20:12:15+14:00"] 165 | expected = zip(test_helper.basic_locations(), expected_dates) 166 | calc = AstronomicalCalendar(date=date(2017, 10, 17)) 167 | 168 | def test_entry(geo): 169 | calc.geo_location = geo 170 | result = calc.sunset_offset_by_degrees(102) 171 | return geo, (None if result is None else result.replace(microsecond=0).isoformat()) 172 | 173 | for entry in expected: 174 | self.assertEqual(test_entry(entry[0]), entry) 175 | 176 | def test_sunset_offset_by_degrees_for_arctic_timezone_extremities(self): 177 | calc = AstronomicalCalendar(date=date(2017, 6, 21)) 178 | calc.geo_location = test_helper.hooper_bay() 179 | result = calc.sunset_offset_by_degrees(94) 180 | self.assertEqual(result.replace(microsecond=0).isoformat(), "2017-06-22T02:00:16-08:00") 181 | 182 | def test_temporal_hour(self): 183 | expected_lengths = [0.92239132, 0.94567431, 0.93889721, 0.93666451, None, 1.03504709] 184 | expected = zip(test_helper.basic_locations(), expected_lengths) 185 | calc = AstronomicalCalendar(date=date(2017, 10, 17)) 186 | 187 | def test_entry(geo): 188 | calc.geo_location = geo 189 | result = calc.temporal_hour() 190 | return geo, (None if result is None else round(result / MathHelper.HOUR_MILLIS, 8)) 191 | 192 | for entry in expected: 193 | self.assertEqual(test_entry(entry[0]), entry) 194 | 195 | def test_sun_transit(self): 196 | expected_dates = ["2017-10-17T12:41:55-04:00", 197 | "2017-10-17T12:24:09+03:00", 198 | "2017-10-17T12:39:45-07:00", 199 | "2017-10-17T11:26:33+09:00", 200 | None, 201 | "2017-10-17T13:12:42+14:00"] 202 | expected = zip(test_helper.basic_locations(), expected_dates) 203 | calc = AstronomicalCalendar(date=date(2017, 10, 17)) 204 | 205 | def test_entry(geo): 206 | calc.geo_location = geo 207 | result = calc.sun_transit() 208 | return geo, (None if result is None else result.replace(microsecond=0).isoformat()) 209 | 210 | for entry in expected: 211 | self.assertEqual(test_entry(entry[0]), entry) 212 | 213 | 214 | if __name__ == '__main__': 215 | unittest.main() -------------------------------------------------------------------------------- /test/test_daf_hashavua_bavli.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from datetime import date, timedelta 3 | 4 | from zmanim.limudim.calculators.daf_hashavua_bavli import DafHashavuaBavli 5 | 6 | 7 | class TestDafHashavuaBavli(unittest.TestCase): 8 | def test_simple_date(self): 9 | test_date = date(2018, 10, 10) 10 | limud = DafHashavuaBavli().limud(test_date) 11 | self.assertEqual(limud.start_date(), test_date - timedelta(days=3)) 12 | self.assertEqual(limud.end_date(), test_date + timedelta(days=3)) 13 | self.assertEqual(limud.description(), 'megillah 3') 14 | 15 | def test_before_cycle_began(self): 16 | test_date = date(2005, 3, 1) 17 | limud = DafHashavuaBavli().limud(test_date) 18 | self.assertIsNone(limud) 19 | 20 | def test_first_day_of_cycle(self): 21 | test_date = date(2057, 2, 11) 22 | limud = DafHashavuaBavli().limud(test_date) 23 | self.assertEqual(limud.description(), 'berachos 2') 24 | 25 | def test_last_day_of_cycle(self): 26 | test_date = date(2057, 2, 10) 27 | limud = DafHashavuaBavli().limud(test_date) 28 | self.assertEqual(limud.description(), 'niddah 73') 29 | -------------------------------------------------------------------------------- /test/test_daf_yomi_bavli_calculator.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from datetime import date 3 | 4 | from zmanim.limudim.calculators.daf_yomi_bavli import DafYomiBavli 5 | 6 | 7 | class TestDafYomiBavliCalculator(unittest.TestCase): 8 | def test_simple_date(self): 9 | test_date = date(2017, 12, 28) 10 | limud = DafYomiBavli().limud(test_date) 11 | self.assertEqual(limud.start_date(), test_date) 12 | self.assertEqual(limud.end_date(), test_date) 13 | self.assertEqual(limud.description(), 'shevuos 30') 14 | 15 | def test_before_cycle_began(self): 16 | test_date = date(1920, 1, 1) 17 | limud = DafYomiBavli().limud(test_date) 18 | self.assertIsNone(limud) 19 | 20 | def test_first_day_of_cycle(self): 21 | test_date = date(2012, 8, 3) 22 | limud = DafYomiBavli().limud(test_date) 23 | self.assertEqual(limud.description(), 'berachos 2') 24 | 25 | def test_last_day_of_cycle(self): 26 | test_date = date(2020, 1, 4) 27 | limud = DafYomiBavli().limud(test_date) 28 | self.assertEqual(limud.description(), 'niddah 73') 29 | 30 | def test_before_shekalim_transition_end_of_shekalim(self): 31 | test_date = date(1969, 4, 28) 32 | limud = DafYomiBavli().limud(test_date) 33 | self.assertEqual(limud.description(), 'shekalim 13') 34 | 35 | def test_before_shekalim_transition_beginning_of_yoma(self): 36 | test_date = date(1969, 4, 29) 37 | limud = DafYomiBavli().limud(test_date) 38 | self.assertEqual(limud.description(), 'yoma 2') 39 | 40 | def test_end_of_meilah(self): 41 | test_date = date(2019, 10, 9) 42 | limud = DafYomiBavli().limud(test_date) 43 | self.assertEqual(limud.description(), 'meilah 22') 44 | 45 | def test_beginning_of_kinnim(self): 46 | test_date = date(2019, 10, 10) 47 | limud = DafYomiBavli().limud(test_date) 48 | self.assertEqual(limud.description(), 'kinnim 23') 49 | 50 | def test_beginning_of_tamid(self): 51 | test_date = date(2019, 10, 13) 52 | limud = DafYomiBavli().limud(test_date) 53 | self.assertEqual(limud.description(), 'tamid 26') 54 | 55 | def test_beginning_of_midos(self): 56 | test_date = date(2019, 10, 22) 57 | limud = DafYomiBavli().limud(test_date) 58 | self.assertEqual(limud.description(), 'midos 35') 59 | 60 | def test_after_midos(self): 61 | test_date = date(2019, 10, 25) 62 | limud = DafYomiBavli().limud(test_date) 63 | self.assertEqual(limud.description(), 'niddah 2') 64 | -------------------------------------------------------------------------------- /test/test_daf_yomi_yerushalmi_calculator.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from datetime import date 3 | 4 | from zmanim.limudim.calculators.daf_yomi_yerushalmi import DafYomiYerushalmi 5 | from zmanim.hebrew_calendar.jewish_date import JewishDate 6 | 7 | 8 | class TestDafYomiYerushalmiCalculator(unittest.TestCase): 9 | def test_simple_date(self): 10 | test_date = date(2017, 12, 28) 11 | limud = DafYomiYerushalmi().limud(test_date) 12 | self.assertEqual(limud.start_date(), test_date) 13 | self.assertEqual(limud.end_date(), test_date) 14 | self.assertEqual(limud.description(), 'bava_metzia 33') 15 | 16 | def test_before_cycle_began(self): 17 | test_date = date(1980, 1, 1) 18 | limud = DafYomiYerushalmi().limud(test_date) 19 | self.assertIsNone(limud) 20 | 21 | def test_first_day_of_cycle(self): 22 | test_date = date(2005, 10, 3) 23 | limud = DafYomiYerushalmi().limud(test_date) 24 | self.assertEqual(limud.description(), 'berachos 1') 25 | 26 | def test_last_day_of_cycle(self): 27 | test_date = date(2010, 1, 12) 28 | limud = DafYomiYerushalmi().limud(test_date) 29 | self.assertEqual(limud.description(), 'niddah 13') 30 | 31 | def test_last_skip_day(self): 32 | test_date = JewishDate(5778, 7, 10) 33 | limud = DafYomiYerushalmi().limud(test_date) 34 | self.assertEqual(limud.start_date(), test_date) 35 | self.assertEqual(limud.end_date(), test_date) 36 | self.assertEqual(limud.description(), 'no_daf_today') 37 | -------------------------------------------------------------------------------- /test/test_geo_location.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from dateutil import parser, tz 4 | 5 | from test import test_helper 6 | from zmanim.util.geo_location import GeoLocation 7 | 8 | 9 | class TestGeoLocation(unittest.TestCase): 10 | 11 | def test_GMT(self): 12 | gmt = GeoLocation.GMT() 13 | self.assertEqual(gmt.location_name, 'Greenwich, England') 14 | self.assertEqual(gmt.longitude, 0) 15 | self.assertEqual(gmt.latitude, 51.4772) 16 | self.assertTrue(gmt.time_zone._filename.endswith('/GMT')) 17 | self.assertEqual(gmt.elevation, 0) 18 | 19 | def test_latitude_numeric(self): 20 | geo = GeoLocation.GMT() 21 | geo.latitude = 33.3 22 | self.assertEqual(geo.latitude, 33.3) 23 | 24 | def test_latitude_cartography_north(self): 25 | geo = GeoLocation.GMT() 26 | geo.latitude = 41, 7, 5.17296, 'N' 27 | self.assertEqual(geo.latitude, 41.1181036) 28 | 29 | def test_latitude_cartography_south(self): 30 | geo = GeoLocation.GMT() 31 | geo.latitude = 41, 7, 5.17296, 'S' 32 | self.assertEqual(geo.latitude, -41.1181036) 33 | 34 | def test_longitude_numeric(self): 35 | geo = GeoLocation.GMT() 36 | geo.longitude = 23.4 37 | self.assertEqual(geo.longitude, 23.4) 38 | 39 | def test_longitude_cartography_east(self): 40 | geo = GeoLocation.GMT() 41 | geo.longitude = 41, 7, 5.17296, 'E' 42 | self.assertEqual(geo.longitude, 41.1181036) 43 | 44 | def test_longitude_cartography_west(self): 45 | geo = GeoLocation.GMT() 46 | geo.longitude = 41, 7, 5.17296, 'W' 47 | self.assertEqual(geo.longitude, -41.1181036) 48 | 49 | def test_time_zone_with_string(self): 50 | geo = GeoLocation.GMT() 51 | geo.time_zone = 'America/New_York' 52 | self.assertTrue(geo.time_zone._filename.endswith('/America/New_York')) 53 | 54 | def test_time_zone_with_timezone_object(self): 55 | geo = GeoLocation.GMT() 56 | geo.time_zone = tz.gettz('America/New_York') 57 | self.assertTrue(geo.time_zone._filename.endswith('/America/New_York')) 58 | 59 | def test_antimeridian_adjustment_for_gmt(self): 60 | geo = GeoLocation.GMT() 61 | self.assertEqual(geo.antimeridian_adjustment(), 0) 62 | 63 | def test_antimeridian_adjustment_for_standard_timezone(self): 64 | geo = GeoLocation.GMT() 65 | geo.time_zone = 'America/New_York' 66 | self.assertEqual(geo.antimeridian_adjustment(), 0) 67 | 68 | def test_antimeridian_adjustment_for_eastward_crossover(self): 69 | geo = test_helper.samoa() 70 | self.assertEqual(geo.antimeridian_adjustment(), -1) 71 | 72 | def test_antimeridian_adjustment_for_westward_crossover(self): 73 | geo = GeoLocation.GMT() 74 | geo.longitude = 179 75 | geo.time_zone = 'Etc/GMT+12' 76 | self.assertEqual(geo.antimeridian_adjustment(), 1) 77 | 78 | def test_local_mean_time_offset_for_gmt(self): 79 | geo = GeoLocation.GMT() 80 | self.assertEqual(geo.local_mean_time_offset(), 0) 81 | 82 | def test_local_mean_time_offset_on_center_meridian(self): 83 | geo = GeoLocation('Sample', 40, -75, 'America/New_York') 84 | self.assertEqual(geo.local_mean_time_offset(), 0) 85 | 86 | def test_local_mean_time_offset_east_of_center_meridian(self): 87 | geo = GeoLocation('Sample', 40, -74, 'America/New_York') 88 | self.assertEqual(geo.local_mean_time_offset(), 1 * 4 * GeoLocation.MINUTE_MILLIS) 89 | 90 | def test_local_mean_time_offset_west_of_center_meridian(self): 91 | geo = GeoLocation('Sample', 40, -76.25, 'America/New_York') 92 | self.assertEqual(geo.local_mean_time_offset(), -1.25 * 4 * GeoLocation.MINUTE_MILLIS) 93 | 94 | def test_standard_time_offset_for_gmt(self): 95 | geo = GeoLocation.GMT() 96 | self.assertEqual(geo.standard_time_offset(), 0) 97 | 98 | def test_standard_time_offset_for_standard_timezone(self): 99 | geo = GeoLocation.GMT() 100 | geo.time_zone = 'America/New_York' 101 | self.assertEqual(geo.standard_time_offset(), -5 * GeoLocation.HOUR_MILLIS) 102 | 103 | def test_time_zone_offset_at(self): 104 | expected = [('2017-03-12T06:30:00Z', 'US/Eastern', -5), 105 | ('2017-03-12T07:00:00Z', 'US/Eastern', -4), 106 | ('2017-03-12T09:30:00Z', 'US/Pacific', -8), 107 | ('2017-03-12T10:00:00Z', 'US/Pacific', -7), 108 | ('2017-03-23T23:30:00Z', 'Asia/Jerusalem', 2), 109 | ('2017-03-24T00:00:00Z', 'Asia/Jerusalem', 3)] 110 | 111 | def test_entry(time, tz): 112 | geo = GeoLocation('Sample', 0, 0, tz) 113 | return time, tz, geo.time_zone_offset_at(parser.parse(time)) 114 | 115 | for entry in expected: 116 | self.assertEqual(test_entry(entry[0], entry[1]), entry) 117 | 118 | 119 | if __name__ == '__main__': 120 | unittest.main() -------------------------------------------------------------------------------- /test/test_helper.py: -------------------------------------------------------------------------------- 1 | from zmanim.hebrew_calendar.jewish_calendar import JewishCalendar 2 | from zmanim.util.geo_location import GeoLocation 3 | 4 | 5 | def lakewood(): 6 | return GeoLocation('Lakewood, NJ', 40.0721087, -74.2400243, 'America/New_York', elevation=15) 7 | 8 | 9 | def samoa(): 10 | return GeoLocation('Apia, Samoa', -13.8599098, -171.8031745, 'Pacific/Apia', elevation=1858) 11 | 12 | 13 | def jerusalem(): 14 | return GeoLocation('Jerusalem, Israel', 31.7781161, 35.233804, 'Asia/Jerusalem', elevation=740) 15 | 16 | 17 | def los_angeles(): 18 | return GeoLocation('Los Angeles, CA', 34.0201613, -118.6919095, 'America/Los_Angeles', elevation=71) 19 | 20 | 21 | def tokyo(): 22 | return GeoLocation('Tokyo, Japan', 35.6733227, 139.6403486, 'Asia/Tokyo', elevation=40) 23 | 24 | 25 | def arctic_nunavut(): 26 | return GeoLocation('Fort Conger, NU Canada', 81.7449398, -64.7945858, 'America/Toronto', elevation=127) 27 | 28 | 29 | def basic_locations(): 30 | return [lakewood(), jerusalem(), los_angeles(), tokyo(), arctic_nunavut(), samoa()] 31 | 32 | 33 | def hooper_bay(): 34 | return GeoLocation('Hooper Bay, Alaska', 61.520182, -166.1740437, 'America/Anchorage', elevation=8) 35 | 36 | 37 | def daneborg(): 38 | return GeoLocation('Daneborg, Greenland', 74.2999996, -20.2420877, 'America/Godthab', elevation=0) 39 | 40 | 41 | def standard_monday_chaseirim(): 42 | return 5777 43 | 44 | 45 | def standard_monday_shelaimim(): 46 | return 5759 47 | 48 | 49 | def standard_tuesday_kesidran(): 50 | return 5762 51 | 52 | 53 | def standard_thursday_kesidran(): 54 | return 5778 55 | 56 | 57 | def standard_thursday_shelaimim(): 58 | return 5754 59 | 60 | 61 | def standard_shabbos_chaseirim(): 62 | return 5781 63 | 64 | 65 | def standard_shabbos_shelaimim(): 66 | return 5770 67 | 68 | 69 | def leap_monday_chaseirim(): 70 | return 5749 71 | 72 | 73 | def leap_monday_shelaimim(): 74 | return 5776 75 | 76 | 77 | def leap_tuesday_kesidran(): 78 | return 5755 79 | 80 | 81 | def leap_thursday_chaseirim(): 82 | return 5765 83 | 84 | 85 | def leap_thursday_shelaimim(): 86 | return 5774 87 | 88 | 89 | def leap_shabbos_chaseirim(): 90 | return 5757 91 | 92 | 93 | def leap_shabbos_shelaimim(): 94 | return 5763 95 | 96 | 97 | def all_days_matching(year, matcher, in_israel=False, use_modern_holidays=False): 98 | calendar = JewishCalendar(year, 7, 1) 99 | calendar.in_israel = in_israel 100 | calendar.use_modern_holidays = use_modern_holidays 101 | collection = {} 102 | while calendar.jewish_year == year: 103 | sd = matcher(calendar) 104 | if sd: 105 | if sd not in collection: 106 | collection[sd] = [] 107 | collection[sd] += [f'{calendar.jewish_month}-{calendar.jewish_day}'] 108 | calendar.forward() 109 | return collection 110 | 111 | 112 | def specific_days_matching(collection, days): 113 | return {day: collection[day] for day in days} 114 | -------------------------------------------------------------------------------- /test/test_limudim_unit.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from zmanim.limudim.unit import Unit 4 | 5 | 6 | class TestLimudimUnit(unittest.TestCase): 7 | def test_str_for_a_primitive_unit(self): 8 | subject = Unit('berachos') 9 | self.assertEqual(str(subject), 'berachos') 10 | 11 | def test_str_for_a_paged_unit(self): 12 | subject = Unit(['berachos', 3]) 13 | self.assertEqual(str(subject), 'berachos 3') 14 | 15 | def test_str_for_a_multi_level_unit_with_integers(self): 16 | subject = Unit(['berachos', 3, 5, 7, 4, 5]) 17 | self.assertEqual(str(subject), 'berachos 3:5:7:4:5') 18 | 19 | def test_str_for_a_multi_level_unit_with_a_character(self): 20 | subject = Unit(['berachos', 'a']) 21 | self.assertEqual(str(subject), 'berachos a') 22 | 23 | def test_str_for_a_multi_level_unit_with_integer_and_then_a_character(self): 24 | subject = Unit(['berachos', 13, 'a']) 25 | self.assertEqual(str(subject), 'berachos 13a') 26 | 27 | def test_str_for_a_multi_level_unit_with_integer_and_then_a_character_and_rlm_marker(self): 28 | subject = Unit(['berachos', 13, u'a\u200f']) 29 | self.assertEqual(str(subject), u'berachos 13a\u200f') 30 | 31 | def test_str_for_a_multi_component_primitive_unit(self): 32 | subject = Unit('tazria', 'metzora') 33 | self.assertEqual(str(subject), 'tazria - metzora') 34 | 35 | def test_str_for_a_multi_component_integer_unit(self): 36 | subject = Unit(18, 25) 37 | self.assertEqual(str(subject), '18 - 25') 38 | 39 | def test_str_for_a_page_spanning_unit_with_similar_root_nodes(self): 40 | subject = Unit(['berachos', 3], ['berachos', 4]) 41 | self.assertEqual(str(subject), 'berachos 3-4') 42 | 43 | def test_str_for_a_page_spanning_unit_with_different_root_nodes(self): 44 | subject = Unit(['berachos', 3], ['shabbos', 4]) 45 | self.assertEqual(str(subject), 'berachos 3 - shabbos 4') 46 | 47 | def test_str_for_a_multi_level_spanning_unit_with_different_leaf_nodes(self): 48 | subject = Unit(['berachos', 3, 5], ['berachos', 3, 7]) 49 | self.assertEqual(str(subject), 'berachos 3:5-7') 50 | 51 | def test_str_for_a_multi_level_spanning_unit_with_different_middle_nodes(self): 52 | subject = Unit(['berachos', 3, 5], ['berachos', 4, 1]) 53 | self.assertEqual(str(subject), 'berachos 3:5-4:1') 54 | 55 | def test_str_for_a_multi_level_spanning_unit_with_different_root_nodes(self): 56 | subject = Unit(['berachos', 9, 1], ['peah', 1, 1]) 57 | self.assertEqual(str(subject), 'berachos 9:1 - peah 1:1') 58 | 59 | def test_render_alters_rendering_using_passed_function(self): 60 | def sample_rendering_function(value): 61 | if isinstance(value, int): 62 | return value * 2 63 | else: 64 | return value.upper() 65 | 66 | subject = Unit(['berachos', 3]) 67 | result = subject.render(sample_rendering_function) 68 | self.assertEqual(result, 'BERACHOS 6') 69 | 70 | 71 | -------------------------------------------------------------------------------- /test/test_mishna_yomis_calculator.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from datetime import date 3 | 4 | from zmanim.limudim.calculators.mishna_yomis import MishnaYomis 5 | 6 | 7 | class TestMishnaYomis(unittest.TestCase): 8 | def test_simple_date(self): 9 | test_date = date(2017, 12, 28) 10 | limud = MishnaYomis().limud(test_date) 11 | self.assertEqual(limud.start_date(), test_date) 12 | self.assertEqual(limud.end_date(), test_date) 13 | self.assertEqual(limud.description(), 'megillah 3:4-5') 14 | 15 | def test_before_cycle_began(self): 16 | test_date = date(1947, 1, 1) 17 | limud = MishnaYomis().limud(test_date) 18 | self.assertIsNone(limud) 19 | 20 | def test_first_day_of_cycle(self): 21 | test_date = date(2016, 3, 30) 22 | limud = MishnaYomis().limud(test_date) 23 | self.assertEqual(limud.description(), 'berachos 1:1-2') 24 | 25 | def test_last_day_of_cycle(self): 26 | test_date = date(2016, 3, 29) 27 | limud = MishnaYomis().limud(test_date) 28 | self.assertEqual(limud.description(), 'uktzin 3:11-12') 29 | 30 | def test_span_two_masechtos(self): 31 | test_date = date(2016, 4, 27) 32 | limud = MishnaYomis().limud(test_date) 33 | self.assertEqual(limud.description(), 'berachos 9:5 - peah 1:1') 34 | 35 | def test_span_two_perakim(self): 36 | test_date = date(2017, 12, 23) 37 | limud = MishnaYomis().limud(test_date) 38 | self.assertEqual(limud.description(), 'megillah 1:11-2:1') 39 | -------------------------------------------------------------------------------- /test/test_noaa_calculator.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from dateutil import parser 4 | 5 | from zmanim.util.geo_location import GeoLocation 6 | from zmanim.util.noaa_calculator import NOAACalculator 7 | 8 | 9 | class TestNOAACalculator(unittest.TestCase): 10 | def test_utc_sunrise(self): 11 | calc = NOAACalculator() 12 | expected = [('2017-10-17', 41.1181036, -74.0840691, 167, 11.13543634), 13 | ('2017-10-17', 34.0201613, -118.6919095, 71, 14.00708152), 14 | ('1955-02-26', 31.7962994, 35.1053185, 754, 4.11885084), 15 | ('2017-06-21', 70.1498248, 9.1456867, 0, None)] 16 | 17 | def test_entry(date, lat, lng, el): 18 | geo = GeoLocation('Sample', lat, lng, 'America/New_York', elevation=el) 19 | result = calc.utc_sunrise(parser.parse(date), geo, 90, True) 20 | return date, lat, lng, el, (None if result is None else round(result, 8)) 21 | 22 | for entry in expected: 23 | self.assertEqual(test_entry(entry[0], entry[1], entry[2], entry[3]), entry) 24 | 25 | def test_utc_sunset(self): 26 | calc = NOAACalculator() 27 | expected = [('2017-10-17', 41.1181036, -74.0840691, 167, 22.24078702), 28 | ('1955-02-26', 31.7962994, 35.1053185, 754, 15.64531391), 29 | ('2017-06-21', 70.1498248, 9.1456867, 0, None)] 30 | 31 | def test_entry(date, lat, lng, el): 32 | geo = GeoLocation('Sample', lat, lng, 'America/New_York', elevation=el) 33 | result = calc.utc_sunset(parser.parse(date), geo, 90, True) 34 | return date, lat, lng, el, (None if result is None else round(result, 8)) 35 | 36 | for entry in expected: 37 | self.assertEqual(test_entry(entry[0], entry[1], entry[2], entry[3]), entry) 38 | 39 | 40 | if __name__ == '__main__': 41 | unittest.main() -------------------------------------------------------------------------------- /test/test_parsha_calculator.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from zmanim.hebrew_calendar.jewish_date import JewishDate 4 | from zmanim.limudim.calculators.parsha import Parsha 5 | 6 | 7 | class TestParshaCalculator(unittest.TestCase): 8 | def test_simple_date(self): 9 | date = JewishDate(5778, 10, 8) 10 | limud = Parsha().limud(date) 11 | self.assertEqual(limud.end_date().jewish_date, (5778, 10, 12)) 12 | self.assertEqual(limud.description(), 'vayechi') 13 | 14 | def test_wraparound_date(self): 15 | date = JewishDate(5777, 6, 27) 16 | limud = Parsha().limud(date) 17 | self.assertEqual(limud.end_date().jewish_date, (5778, 7, 3)) 18 | self.assertEqual(limud.description(), 'haazinu') 19 | 20 | def test_date_before_cycle_restarts(self): 21 | date = JewishDate(5778, 7, 4) 22 | limud = Parsha().limud(date) 23 | self.assertEqual(limud.end_date().jewish_date, (5778, 7, 23)) 24 | self.assertEqual(limud.description(), 'vezos_haberacha') 25 | 26 | def test_disparate_parsha_in_israel(self): 27 | date = JewishDate(5775, 1, 27) 28 | limud = Parsha(in_israel=True).limud(date) 29 | self.assertEqual(limud.end_date().jewish_date, (5775, 1, 29)) 30 | self.assertEqual(limud.description(), 'tazria - metzora') 31 | 32 | def test_disparate_parsha_outside_israel(self): 33 | date = JewishDate(5775, 1, 27) 34 | limud = Parsha().limud(date) 35 | self.assertEqual(limud.end_date().jewish_date, (5775, 1, 29)) 36 | self.assertEqual(limud.description(), 'shemini') 37 | -------------------------------------------------------------------------------- /test/test_pirkei_avos_calculator.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from zmanim.hebrew_calendar.jewish_date import JewishDate 4 | from zmanim.limudim.calculators.pirkei_avos import PirkeiAvos 5 | 6 | 7 | class TestPirkeiAvosCalculator(unittest.TestCase): 8 | def test_simple_date(self): 9 | test_date = JewishDate(5778, 3, 1) 10 | limud = PirkeiAvos().limud(test_date) 11 | self.assertEqual(limud.end_date(), JewishDate(5778, 3, 5)) 12 | self.assertEqual(limud.description(), '6') 13 | 14 | def test_near_end_of_cycle(self): 15 | test_date = JewishDate(5778, 6, 20) 16 | limud = PirkeiAvos().limud(test_date) 17 | self.assertEqual(limud.end_date(), JewishDate(5778, 6, 21)) 18 | self.assertEqual(limud.description(), '3 - 4') 19 | 20 | def test_after_cycle_completes(self): 21 | test_date = JewishDate(5778, 6, 29) 22 | limud = PirkeiAvos().limud(test_date) 23 | self.assertIsNone(limud) 24 | 25 | def test_before_cycle_starts(self): 26 | test_date = JewishDate(5778, 1, 20) 27 | limud = PirkeiAvos().limud(test_date) 28 | self.assertIsNone(limud) 29 | 30 | def test_8th_day_pesach_outside_israel(self): 31 | test_date = JewishDate(5778, 1, 22) 32 | limud = PirkeiAvos().limud(test_date) 33 | self.assertIsNone(limud) 34 | 35 | def test_day_after_pesach_outside_israel(self): 36 | test_date = JewishDate(5778, 1, 23) 37 | limud = PirkeiAvos().limud(test_date) 38 | self.assertEqual(limud.end_date(), JewishDate(5778, 1, 29)) 39 | self.assertEqual(limud.description(), '1') 40 | 41 | def test_compounding_before_cycle_end_outside_israel(self): 42 | test_date = JewishDate(5778, 6, 14) 43 | limud = PirkeiAvos().limud(test_date) 44 | self.assertEqual(limud.description(), '2') 45 | test_date = JewishDate(5778, 6, 15) 46 | limud = PirkeiAvos().limud(test_date) 47 | self.assertEqual(limud.description(), '3 - 4') 48 | 49 | def test_8th_day_pesach_in_israel(self): 50 | test_date = JewishDate(5778, 1, 22) 51 | limud = PirkeiAvos(in_israel=True).limud(test_date) 52 | self.assertEqual(limud.end_date(), JewishDate(5778, 1, 22)) 53 | self.assertEqual(limud.description(), '1') 54 | 55 | def test_day_after_pesach_in_israel(self): 56 | test_date = JewishDate(5778, 1, 23) 57 | limud = PirkeiAvos(in_israel=True).limud(test_date) 58 | self.assertEqual(limud.end_date(), JewishDate(5778, 1, 29)) 59 | self.assertEqual(limud.description(), '2') 60 | 61 | def test_compounding_before_cycle_end_in_israel(self): 62 | test_date = JewishDate(5778, 6, 21) 63 | limud = PirkeiAvos(in_israel=True).limud(test_date) 64 | self.assertEqual(limud.description(), '4') 65 | test_date = JewishDate(5778, 6, 22) 66 | limud = PirkeiAvos().limud(test_date) 67 | self.assertEqual(limud.description(), '5 - 6') 68 | 69 | def test_7_iyar_on_shabbos_outside_israel_has_blank_limud(self): 70 | test_date = JewishDate(5769, 3, 3) 71 | limud = PirkeiAvos().limud(test_date) 72 | self.assertEqual(limud.end_date(), JewishDate(5769, 3, 7)) 73 | self.assertIsNone(limud.unit) 74 | 75 | def test_iteration_following_7_iyar_on_shabbos_outside_israel_starts_new_subcycle(self): 76 | test_date = JewishDate(5769, 3, 8) 77 | limud = PirkeiAvos().limud(test_date) 78 | self.assertEqual(limud.end_date(), JewishDate(5769, 3, 14)) 79 | self.assertEqual(limud.description(), '1') 80 | 81 | def test_7_iyar_on_shabbos_outside_israel_compounds_last_3_weeks(self): 82 | test_date = JewishDate(5769, 6, 2) 83 | limud = PirkeiAvos().limud(test_date) 84 | self.assertEqual(limud.description(), '6') 85 | test_date = JewishDate(5769, 6, 3) 86 | limud = PirkeiAvos().limud(test_date) 87 | self.assertEqual(limud.description(), '1 - 2') 88 | 89 | def test_7_iyar_on_shabbos_is_israel_starts_new_subcycle(self): 90 | test_date = JewishDate(5769, 3, 3) 91 | limud = PirkeiAvos(in_israel=True).limud(test_date) 92 | self.assertEqual(limud.end_date(), JewishDate(5769, 3, 7)) 93 | self.assertEqual(limud.description(), '1') 94 | 95 | def test_iteration_following_7_iyar_on_shabbos_in_israel_starts_next_unit(self): 96 | test_date = JewishDate(5769, 3, 8) 97 | limud = PirkeiAvos(in_israel=True).limud(test_date) 98 | self.assertEqual(limud.end_date(), JewishDate(5769, 3, 14)) 99 | self.assertEqual(limud.description(), '2') 100 | 101 | def test_7_iyar_on_shabbos_in_israel_compounds_last_2_weeks(self): 102 | test_date = JewishDate(5769, 6, 9) 103 | limud = PirkeiAvos(in_israel=True).limud(test_date) 104 | self.assertEqual(limud.description(), '2') 105 | test_date = JewishDate(5769, 6, 10) 106 | limud = PirkeiAvos(in_israel=True).limud(test_date) 107 | self.assertEqual(limud.description(), '3 - 4') 108 | -------------------------------------------------------------------------------- /test/test_sun_times_calculator.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from dateutil import parser 4 | 5 | from zmanim.util.geo_location import GeoLocation 6 | from zmanim.util.sun_times_calculator import SunTimesCalculator 7 | 8 | 9 | class TestSunTimesCalculator(unittest.TestCase): 10 | def test_utc_sunrise(self): 11 | calc = SunTimesCalculator() 12 | expected = [('2017-10-17', 41.1181036, -74.0840691, 0.167, 11.16276401), 13 | ('1955-02-26', 31.7962994, 35.1053185, 0.754, 4.17848602), 14 | ('2017-06-21', 70.1498248, 9.1456867, 0, None)] 15 | 16 | def test_entry(date, lat, lng, el): 17 | geo = GeoLocation('Sample', lat, lng, 'America/New_York', elevation=el) 18 | result = calc.utc_sunrise(parser.parse(date), geo, 90, True) 19 | return date, lat, lng, el, (None if result is None else round(result, 8)) 20 | 21 | for entry in expected: 22 | self.assertEqual(test_entry(entry[0], entry[1], entry[2], entry[3]), entry) 23 | 24 | def test_utc_sunset(self): 25 | calc = SunTimesCalculator() 26 | expected = [('2017-10-17', 41.1181036, -74.0840691, 0.167, 22.21747591), 27 | ('1955-02-26', 31.7962994, 35.1053185, 0.754, 15.58295081), 28 | ('2017-06-21', 70.1498248, 9.1456867, 0, None)] 29 | 30 | def test_entry(date, lat, lng, el): 31 | geo = GeoLocation('Sample', lat, lng, 'America/New_York', elevation=el) 32 | result = calc.utc_sunset(parser.parse(date), geo, 90, True) 33 | return date, lat, lng, el, (None if result is None else round(result, 8)) 34 | 35 | for entry in expected: 36 | self.assertEqual(test_entry(entry[0], entry[1], entry[2], entry[3]), entry) 37 | 38 | 39 | if __name__ == '__main__': 40 | unittest.main() -------------------------------------------------------------------------------- /test/test_tehillim_monthly_calculator.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from zmanim.hebrew_calendar.jewish_date import JewishDate 4 | from zmanim.limudim.calculators.tehillim_monthly import TehillimMonthly 5 | 6 | 7 | class TestTehillimMonthlyCalculator(unittest.TestCase): 8 | def test_simple_date(self): 9 | test_date = JewishDate(5778, 10, 8) 10 | limud = TehillimMonthly().limud(test_date) 11 | self.assertEqual(limud.start_date(), test_date) 12 | self.assertEqual(limud.end_date(), test_date) 13 | self.assertEqual(limud.description(), '44 - 48') 14 | 15 | def test_beginning_of_month(self): 16 | test_date = JewishDate(5778, 10, 1) 17 | limud = TehillimMonthly().limud(test_date) 18 | self.assertEqual(limud.description(), '1 - 9') 19 | 20 | def test_end_of_short_month(self): 21 | test_date = JewishDate(5778, 10, 29) 22 | limud = TehillimMonthly().limud(test_date) 23 | self.assertEqual(limud.description(), '140 - 150') 24 | 25 | def test_end_of_long_month(self): 26 | test_date = JewishDate(5778, 11, 30) 27 | limud = TehillimMonthly().limud(test_date) 28 | self.assertEqual(limud.description(), '145 - 150') 29 | 30 | def test_29th_day_of_long_month(self): 31 | test_date = JewishDate(5778, 11, 29) 32 | limud = TehillimMonthly().limud(test_date) 33 | self.assertEqual(limud.description(), '140 - 144') 34 | 35 | def test_day_25_special_case(self): 36 | test_date = JewishDate(5778, 11, 25) 37 | limud = TehillimMonthly().limud(test_date) 38 | self.assertEqual(limud.description(), '119 1-30') 39 | 40 | def test_day_26_special_case(self): 41 | test_date = JewishDate(5778, 11, 26) 42 | limud = TehillimMonthly().limud(test_date) 43 | self.assertEqual(limud.description(), '119 40-400') 44 | -------------------------------------------------------------------------------- /test/test_zmanim_calendar.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from datetime import date, timedelta 3 | 4 | from dateutil import parser 5 | 6 | from test import test_helper 7 | from zmanim.zmanim_calendar import ZmanimCalendar 8 | 9 | 10 | class TestZmanimCalendar(unittest.TestCase): 11 | def test_hanetz(self): 12 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 13 | self.assertEqual(calendar.hanetz(), calendar.sea_level_sunrise()) 14 | 15 | def test_shkia(self): 16 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 17 | self.assertEqual(calendar.shkia(), calendar.sea_level_sunset()) 18 | 19 | def test_tzais(self): 20 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 21 | self.assertEqual(calendar.tzais().replace(microsecond=0).isoformat(), "2017-10-17T18:54:29-04:00") 22 | 23 | def test_tzais_with_custom_degree_offset(self): 24 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 25 | self.assertEqual(calendar.tzais({'degrees': 19.8}).replace(microsecond=0).isoformat(), "2017-10-17T19:53:34-04:00") 26 | 27 | def test_tzais_with_custom_minute_offset(self): 28 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 29 | self.assertEqual(calendar.tzais({'offset': 60}).replace(microsecond=0).isoformat(), "2017-10-17T19:13:58-04:00") 30 | 31 | def test_tzais_with_custom_temporal_minute_offset(self): 32 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 33 | self.assertEqual(calendar.tzais({'zmanis_offset': 90}).replace(microsecond=0).isoformat(), "2017-10-17T19:36:59-04:00") 34 | 35 | def test_tzais_72(self): 36 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 37 | self.assertEqual(calendar.tzais_72().replace(microsecond=0).isoformat(), "2017-10-17T19:25:58-04:00") 38 | 39 | def test_alos(self): 40 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 41 | self.assertEqual(calendar.alos().replace(microsecond=0).isoformat(), "2017-10-17T05:49:30-04:00") 42 | 43 | def test_alos_with_custom_degree_offset(self): 44 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 45 | self.assertEqual(calendar.alos({'degrees': 19.8}).replace(microsecond=0).isoformat(), "2017-10-17T05:30:07-04:00") 46 | 47 | def test_alos_with_custom_minute_offset(self): 48 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 49 | self.assertEqual(calendar.alos({'offset': 60}).replace(microsecond=0).isoformat(), "2017-10-17T06:09:51-04:00") 50 | 51 | def test_alos_with_custom_temporal_minute_offset(self): 52 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 53 | self.assertEqual(calendar.alos({'zmanis_offset': 90}).replace(microsecond=0).isoformat(), "2017-10-17T05:46:50-04:00") 54 | 55 | def test_alos_72(self): 56 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 57 | self.assertEqual(calendar.alos_72().replace(microsecond=0).isoformat(), "2017-10-17T05:57:51-04:00") 58 | 59 | def test_chatzos(self): 60 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 61 | self.assertEqual(calendar.chatzos().replace(microsecond=0).isoformat(), "2017-10-17T12:41:55-04:00") 62 | 63 | def test_sof_zman_shma(self): 64 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 65 | day_start = calendar.sunrise_offset_by_degrees(96) 66 | day_end = calendar.sunset_offset_by_degrees(96) 67 | self.assertEqual(calendar.sof_zman_shma(day_start, day_end).replace(microsecond=0).isoformat(), "2017-10-17T09:42:10-04:00") 68 | 69 | def test_sof_zman_shma_gra(self): 70 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 71 | self.assertEqual(calendar.sof_zman_shma_gra().replace(microsecond=0).isoformat(), "2017-10-17T09:55:53-04:00") 72 | 73 | def test_sof_zman_shma_mga(self): 74 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 75 | self.assertEqual(calendar.sof_zman_shma_mga().replace(microsecond=0).isoformat(), "2017-10-17T09:19:53-04:00") 76 | 77 | def test_sof_zman_tfila(self): 78 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 79 | day_start = calendar.sunrise_offset_by_degrees(96) 80 | day_end = calendar.sunset_offset_by_degrees(96) 81 | self.assertEqual(calendar.sof_zman_tfila(day_start, day_end).replace(microsecond=0).isoformat(), "2017-10-17T10:42:05-04:00") 82 | 83 | def test_sof_zman_tfila_gra(self): 84 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 85 | self.assertEqual(calendar.sof_zman_tfila_gra().replace(microsecond=0).isoformat(), "2017-10-17T10:51:14-04:00") 86 | 87 | def test_sof_zman_tfila_mga(self): 88 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 89 | self.assertEqual(calendar.sof_zman_tfila_mga().replace(microsecond=0).isoformat(), "2017-10-17T10:27:14-04:00") 90 | 91 | def test_mincha_gedola(self): 92 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 93 | self.assertEqual(calendar.mincha_gedola().replace(microsecond=0).isoformat(), "2017-10-17T13:09:35-04:00") 94 | 95 | def test_mincha_ketana(self): 96 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 97 | self.assertEqual(calendar.mincha_ketana().replace(microsecond=0).isoformat(), "2017-10-17T15:55:37-04:00") 98 | 99 | def test_plag_hamincha(self): 100 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 101 | self.assertEqual(calendar.plag_hamincha().replace(microsecond=0).isoformat(), "2017-10-17T17:04:48-04:00") 102 | 103 | def test_candle_lighting(self): 104 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 105 | self.assertEqual(calendar.candle_lighting().replace(microsecond=0).isoformat(), "2017-10-17T17:55:58-04:00") 106 | 107 | def test_shaah_zmanis(self): 108 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 109 | day_start = calendar.sunrise_offset_by_degrees(96) 110 | day_end = calendar.sunset_offset_by_degrees(96) 111 | self.assertEqual(int(calendar.shaah_zmanis(day_start, day_end)), 3594499) 112 | 113 | def test_shaah_zmanis_gra(self): 114 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 115 | self.assertEqual(int(calendar.shaah_zmanis_gra()), 3320608) 116 | 117 | def test_shaah_zmanis_mga(self): 118 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 119 | self.assertEqual(int(calendar.shaah_zmanis_mga()), 4040608) 120 | 121 | def test_shaah_zmanis_by_degrees_and_offset_with_degrees(self): 122 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 123 | self.assertEqual(int(calendar.shaah_zmanis_by_degrees_and_offset(6, 0)), 3594499) 124 | 125 | def test_shaah_zmanis_by_degrees_and_offset_with_offset(self): 126 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 127 | self.assertEqual(int(calendar.shaah_zmanis_by_degrees_and_offset(0, 72)), 4040608) 128 | 129 | def test_shaah_zmanis_by_degrees_and_offset_with_both_degrees_and_offset(self): 130 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 131 | self.assertEqual(int(calendar.shaah_zmanis_by_degrees_and_offset(6, 72)), 4314499) 132 | 133 | def test_hanetz_using_elevation(self): 134 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 135 | calendar.use_elevation = True 136 | self.assertEqual(calendar.hanetz(), calendar.sunrise()) 137 | 138 | def test_shkia_using_elevation(self): 139 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 140 | calendar.use_elevation = True 141 | self.assertEqual(calendar.shkia(), calendar.sunset()) 142 | 143 | def test_tzais_using_elevation(self): 144 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 145 | calendar.use_elevation = True 146 | self.assertEqual(calendar.tzais().replace(microsecond=0).isoformat(), "2017-10-17T18:54:29-04:00") 147 | 148 | def test_tzais_with_custom_degree_offset_using_elevation(self): 149 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 150 | calendar.use_elevation = True 151 | self.assertEqual(calendar.tzais({'degrees': 19.8}).replace(microsecond=0).isoformat(), "2017-10-17T19:53:34-04:00") 152 | 153 | def test_tzais_with_custom_minute_offset_using_elevation(self): 154 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 155 | calendar.use_elevation = True 156 | self.assertEqual(calendar.tzais({'offset': 60}).replace(microsecond=0).isoformat(), "2017-10-17T19:14:38-04:00") 157 | 158 | def test_tzais_with_custom_temporal_minute_offset_using_elevation(self): 159 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 160 | calendar.use_elevation = True 161 | self.assertEqual(calendar.tzais({'zmanis_offset': 90}).replace(microsecond=0).isoformat(), "2017-10-17T19:37:49-04:00") 162 | 163 | def test_tzais_72_using_elevation(self): 164 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 165 | calendar.use_elevation = True 166 | self.assertEqual(calendar.tzais_72().replace(microsecond=0).isoformat(), "2017-10-17T19:26:38-04:00") 167 | 168 | def test_alos_using_elevation(self): 169 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 170 | calendar.use_elevation = True 171 | self.assertEqual(calendar.alos().replace(microsecond=0).isoformat(), "2017-10-17T05:49:30-04:00") 172 | 173 | def test_alos_with_custom_degree_offset_using_elevation(self): 174 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 175 | calendar.use_elevation = True 176 | self.assertEqual(calendar.alos({'degrees': 19.8}).replace(microsecond=0).isoformat(), "2017-10-17T05:30:07-04:00") 177 | 178 | def test_alos_with_custom_minute_offset_using_elevation(self): 179 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 180 | calendar.use_elevation = True 181 | self.assertEqual(calendar.alos({'offset': 60}).replace(microsecond=0).isoformat(), "2017-10-17T06:09:11-04:00") 182 | 183 | def test_alos_with_custom_temporal_minute_offset_using_elevation(self): 184 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 185 | calendar.use_elevation = True 186 | self.assertEqual(calendar.alos({'zmanis_offset': 90}).replace(microsecond=0).isoformat(), "2017-10-17T05:46:00-04:00") 187 | 188 | def test_alos_72_using_elevation(self): 189 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 190 | calendar.use_elevation = True 191 | self.assertEqual(calendar.alos_72().replace(microsecond=0).isoformat(), "2017-10-17T05:57:11-04:00") 192 | 193 | def test_chatzos_using_elevation(self): 194 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 195 | calendar.use_elevation = True 196 | self.assertEqual(calendar.chatzos().replace(microsecond=0).isoformat(), "2017-10-17T12:41:55-04:00") 197 | 198 | def test_sof_zman_shma_using_elevation(self): 199 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 200 | calendar.use_elevation = True 201 | day_start = calendar.sunrise_offset_by_degrees(96) 202 | day_end = calendar.sunset_offset_by_degrees(96) 203 | self.assertEqual(calendar.sof_zman_shma(day_start, day_end).replace(microsecond=0).isoformat(), "2017-10-17T09:42:10-04:00") 204 | 205 | def test_sof_zman_shma_gra_using_elevation(self): 206 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 207 | calendar.use_elevation = True 208 | self.assertEqual(calendar.sof_zman_shma_gra().replace(microsecond=0).isoformat(), "2017-10-17T09:55:33-04:00") 209 | 210 | def test_sof_zman_shma_mga_using_elevation(self): 211 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 212 | calendar.use_elevation = True 213 | self.assertEqual(calendar.sof_zman_shma_mga().replace(microsecond=0).isoformat(), "2017-10-17T09:19:33-04:00") 214 | 215 | def test_sof_zman_tfila_using_elevation(self): 216 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 217 | calendar.use_elevation = True 218 | day_start = calendar.sunrise_offset_by_degrees(96) 219 | day_end = calendar.sunset_offset_by_degrees(96) 220 | self.assertEqual(calendar.sof_zman_tfila(day_start, day_end).replace(microsecond=0).isoformat(), "2017-10-17T10:42:05-04:00") 221 | 222 | def test_sof_zman_tfila_gra_using_elevation(self): 223 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 224 | calendar.use_elevation = True 225 | self.assertEqual(calendar.sof_zman_tfila_gra().replace(microsecond=0).isoformat(), "2017-10-17T10:51:00-04:00") 226 | 227 | def test_sof_zman_tfila_mga_using_elevation(self): 228 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 229 | calendar.use_elevation = True 230 | self.assertEqual(calendar.sof_zman_tfila_mga().replace(microsecond=0).isoformat(), "2017-10-17T10:27:00-04:00") 231 | 232 | def test_mincha_gedola_using_elevation(self): 233 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 234 | calendar.use_elevation = True 235 | self.assertEqual(calendar.mincha_gedola().replace(microsecond=0).isoformat(), "2017-10-17T13:09:38-04:00") 236 | 237 | def test_mincha_ketana_using_elevation(self): 238 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 239 | calendar.use_elevation = True 240 | self.assertEqual(calendar.mincha_ketana().replace(microsecond=0).isoformat(), "2017-10-17T15:56:00-04:00") 241 | 242 | def test_plag_hamincha_using_elevation(self): 243 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 244 | calendar.use_elevation = True 245 | self.assertEqual(calendar.plag_hamincha().replace(microsecond=0).isoformat(), "2017-10-17T17:05:19-04:00") 246 | 247 | def test_candle_lighting_using_elevation(self): 248 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 249 | calendar.use_elevation = True 250 | self.assertEqual(calendar.candle_lighting().replace(microsecond=0).isoformat(), "2017-10-17T17:55:58-04:00") 251 | 252 | def test_shaah_zmanis_using_elevation(self): 253 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 254 | calendar.use_elevation = True 255 | day_start = calendar.sunrise_offset_by_degrees(96) 256 | day_end = calendar.sunset_offset_by_degrees(96) 257 | self.assertEqual(int(calendar.shaah_zmanis(day_start, day_end)), 3594499) 258 | 259 | def test_shaah_zmanis_gra_using_elevation(self): 260 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 261 | calendar.use_elevation = True 262 | self.assertEqual(int(calendar.shaah_zmanis_gra()), 3327251) 263 | 264 | def test_shaah_zmanis_mga_using_elevation(self): 265 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 266 | calendar.use_elevation = True 267 | self.assertEqual(int(calendar.shaah_zmanis_mga()), 4047251) 268 | 269 | def test_shaah_zmanis_by_degrees_and_offset_with_degrees_using_elevation(self): 270 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 271 | calendar.use_elevation = True 272 | self.assertEqual(int(calendar.shaah_zmanis_by_degrees_and_offset(6, 0)), 3594499) 273 | 274 | def test_shaah_zmanis_by_degrees_and_offset_with_offset_using_elevation(self): 275 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 276 | calendar.use_elevation = True 277 | self.assertEqual(int(calendar.shaah_zmanis_by_degrees_and_offset(0, 72)), 4047251) 278 | 279 | def test_shaah_zmanis_by_degrees_and_offset_with_both_degrees_and_offset_using_elevation(self): 280 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=date(2017, 10, 17)) 281 | calendar.use_elevation = True 282 | self.assertEqual(int(calendar.shaah_zmanis_by_degrees_and_offset(6, 72)), 4314499) 283 | 284 | def test_assur_bemelacha_for_standard_day(self): 285 | date = '2017-10-17' 286 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=parser.parse(date)) 287 | self.assertFalse(calendar.is_assur_bemelacha(calendar.shkia() - timedelta(seconds=2))) 288 | self.assertFalse(calendar.is_assur_bemelacha(calendar.tzais() - timedelta(seconds=2))) 289 | self.assertFalse(calendar.is_assur_bemelacha(calendar.tzais() + timedelta(seconds=2))) 290 | 291 | def test_assur_bemelacha_for_issur_melacha_day(self): 292 | date = '2017-10-21' 293 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=parser.parse(date)) 294 | self.assertTrue(calendar.is_assur_bemelacha(calendar.shkia() - timedelta(seconds=2))) 295 | self.assertTrue(calendar.is_assur_bemelacha(calendar.tzais() - timedelta(seconds=2))) 296 | self.assertFalse(calendar.is_assur_bemelacha(calendar.tzais() + timedelta(seconds=2))) 297 | 298 | def test_assur_bemelacha_for_issur_melacha_day_with_custom_tzais_time(self): 299 | date = '2017-10-21' 300 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=parser.parse(date)) 301 | tzais = calendar.tzais_72() 302 | self.assertTrue(calendar.is_assur_bemelacha(tzais - timedelta(seconds=2), tzais)) 303 | self.assertFalse(calendar.is_assur_bemelacha(tzais + timedelta(seconds=2), tzais)) 304 | 305 | def test_assur_bemelacha_for_issur_melacha_day_with_custom_tzais_rule(self): 306 | date = '2017-10-21' 307 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=parser.parse(date)) 308 | tzais = calendar.tzais({'degrees': 11.5}) 309 | self.assertTrue(calendar.is_assur_bemelacha(tzais - timedelta(seconds=2), {'degrees': 11.5})) 310 | self.assertFalse(calendar.is_assur_bemelacha(tzais + timedelta(seconds=2), {'degrees': 11.5})) 311 | 312 | def test_assur_bemelacha_prior_to_issur_melacha_day(self): 313 | date = '2017-10-20' 314 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=parser.parse(date)) 315 | self.assertFalse(calendar.is_assur_bemelacha(calendar.shkia() - timedelta(seconds=2))) 316 | self.assertTrue(calendar.is_assur_bemelacha(calendar.tzais() - timedelta(seconds=2))) 317 | self.assertTrue(calendar.is_assur_bemelacha(calendar.tzais() + timedelta(seconds=2))) 318 | 319 | def test_assur_bemelacha_on_first_of_two_issur_melacha_days(self): 320 | date = '2018-03-31' # first day of pesach 321 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=parser.parse(date)) 322 | self.assertTrue(calendar.is_assur_bemelacha(calendar.shkia() - timedelta(seconds=2))) 323 | self.assertTrue(calendar.is_assur_bemelacha(calendar.tzais() - timedelta(seconds=2))) 324 | self.assertTrue(calendar.is_assur_bemelacha(calendar.tzais() + timedelta(seconds=2))) 325 | 326 | def test_assur_bemelacha_on_first_of_single_issur_melacha_in_israel(self): 327 | date = '2018-03-31' # first day of pesach 328 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=parser.parse(date)) 329 | self.assertTrue(calendar.is_assur_bemelacha(calendar.tzais() - timedelta(seconds=2), in_israel=True)) 330 | self.assertFalse(calendar.is_assur_bemelacha(calendar.tzais() + timedelta(seconds=2), in_israel=True)) 331 | 332 | def test_assur_bemelacha_on_first_of_two_issur_melacha_days_in_israel(self): 333 | date = '2018-05-19' # Shabbos before Shavuos 334 | calendar = ZmanimCalendar(geo_location=test_helper.lakewood(), date=parser.parse(date)) 335 | self.assertTrue(calendar.is_assur_bemelacha(calendar.tzais() - timedelta(seconds=2), in_israel=True)) 336 | self.assertTrue(calendar.is_assur_bemelacha(calendar.tzais() + timedelta(seconds=2), in_israel=True)) 337 | 338 | 339 | if __name__ == '__main__': 340 | unittest.main() -------------------------------------------------------------------------------- /zmanim/__init__.py: -------------------------------------------------------------------------------- 1 | name = 'zmanim' 2 | -------------------------------------------------------------------------------- /zmanim/astronomical_calendar.py: -------------------------------------------------------------------------------- 1 | from datetime import date, datetime, timedelta 2 | from typing import Optional 3 | 4 | from dateutil import tz 5 | 6 | from zmanim.util.astronomical_calculations import AstronomicalCalculations 7 | from zmanim.util.geo_location import GeoLocation 8 | from zmanim.util.math_helper import MathHelper 9 | from zmanim.util.noaa_calculator import NOAACalculator 10 | 11 | 12 | class AstronomicalCalendar(MathHelper): 13 | GEOMETRIC_ZENITH = 90 14 | CIVIL_ZENITH = 96 15 | NAUTICAL_ZENITH = 102 16 | ASTRONOMICAL_ZENITH = 108 17 | 18 | __sentinel = object() 19 | 20 | def __init__(self, geo_location: Optional[GeoLocation] = None, date: Optional[date] = None, calculator: Optional[AstronomicalCalculations] = None): 21 | if geo_location is None: 22 | geo_location = GeoLocation.GMT() 23 | if date is None: 24 | date = datetime.today() 25 | if calculator is None: 26 | calculator = NOAACalculator() 27 | self.geo_location = geo_location 28 | self.date = date 29 | self.astronomical_calculator = calculator 30 | 31 | def __repr__(self): 32 | return "%s(geo_location=%r, date=%r, calculator=%r)" % \ 33 | (self.__module__ + "." + self.__class__.__qualname__, self.geo_location, self.date, self.astronomical_calculator) 34 | 35 | def sunrise(self) -> Optional[datetime]: 36 | return self._date_time_from_time_of_day(self.utc_sunrise(self.GEOMETRIC_ZENITH), 'sunrise') 37 | 38 | def sea_level_sunrise(self) -> Optional[datetime]: 39 | return self.sunrise_offset_by_degrees(self.GEOMETRIC_ZENITH) 40 | 41 | def sunrise_offset_by_degrees(self, offset_zenith: float) -> Optional[datetime]: 42 | return self._date_time_from_time_of_day(self.utc_sea_level_sunrise(offset_zenith), 'sunrise') 43 | 44 | def sunset(self) -> Optional[datetime]: 45 | return self._date_time_from_time_of_day(self.utc_sunset(self.GEOMETRIC_ZENITH), 'sunset') 46 | 47 | def sea_level_sunset(self) -> Optional[datetime]: 48 | return self.sunset_offset_by_degrees(self.GEOMETRIC_ZENITH) 49 | 50 | def sunset_offset_by_degrees(self, offset_zenith: float) -> Optional[datetime]: 51 | return self._date_time_from_time_of_day(self.utc_sea_level_sunset(offset_zenith), 'sunset') 52 | 53 | def utc_sunrise(self, zenith: float) -> Optional[float]: 54 | return self.astronomical_calculator.utc_sunrise(self._adjusted_date(), self.geo_location, zenith, adjust_for_elevation=True) 55 | 56 | def utc_sea_level_sunrise(self, zenith: float) -> Optional[float]: 57 | return self.astronomical_calculator.utc_sunrise(self._adjusted_date(), self.geo_location, zenith, adjust_for_elevation=False) 58 | 59 | def utc_sunset(self, zenith: float) -> Optional[float]: 60 | return self.astronomical_calculator.utc_sunset(self._adjusted_date(), self.geo_location, zenith, adjust_for_elevation=True) 61 | 62 | def utc_sea_level_sunset(self, zenith: float) -> Optional[float]: 63 | return self.astronomical_calculator.utc_sunset(self._adjusted_date(), self.geo_location, zenith, adjust_for_elevation=False) 64 | 65 | def temporal_hour(self, sunrise: Optional[datetime] = __sentinel, sunset: Optional[datetime] = __sentinel) -> Optional[float]: 66 | if sunrise == self.__sentinel: 67 | sunrise = self.sea_level_sunrise() 68 | if sunset == self.__sentinel: 69 | sunset = self.sea_level_sunset() 70 | 71 | if sunset is None or sunrise is None: 72 | return None 73 | 74 | daytime_hours = float((sunset - sunrise).total_seconds() / 3600.0) 75 | return (daytime_hours / 12) * self.HOUR_MILLIS 76 | 77 | def sun_transit(self) -> Optional[datetime]: 78 | sunrise = self.sea_level_sunrise() 79 | sunset = self.sea_level_sunset() 80 | if sunrise is None or sunset is None: 81 | return None 82 | noon_hour = (self.temporal_hour(sunrise, sunset) / self.HOUR_MILLIS) * 6.0 83 | return sunrise + timedelta(noon_hour / 24.0) 84 | 85 | def _date_time_from_time_of_day(self, time_of_day: Optional[float], mode: str) -> Optional[datetime]: 86 | if time_of_day is None: 87 | return None 88 | 89 | hours, remainder = divmod(time_of_day * 3600, 3600) 90 | minutes, remainder = divmod(remainder, 60) 91 | seconds, microseconds = divmod(remainder * 10**6, 10**6) 92 | adjusted_date = self._adjusted_date() 93 | year, month, day = adjusted_date.year, adjusted_date.month, adjusted_date.day 94 | utc_time = datetime(year, month, day, int(hours), int(minutes), int(seconds), int(microseconds), tzinfo=tz.tzutc()) 95 | 96 | # adjust date if utc time reflects a wraparound from the local offset 97 | local_offset = (self.geo_location.local_mean_time_offset() + self.geo_location.standard_time_offset()) / self.HOUR_MILLIS 98 | if hours + local_offset > 18 and mode == 'sunrise': # sunrise after 6pm indicates the UTC date has occurred earlier 99 | utc_time -= timedelta(1) 100 | elif hours + local_offset < 6 and mode == 'sunset': # sunset before 6am indicates the UTC date has occurred later 101 | utc_time += timedelta(1) 102 | 103 | return self._convert_date_time_for_zone(utc_time) 104 | 105 | def _adjusted_date(self) -> date: 106 | return self.date + timedelta(days=self.geo_location.antimeridian_adjustment()) 107 | 108 | def _convert_date_time_for_zone(self, utc_time: datetime) -> datetime: 109 | return utc_time.astimezone(self.geo_location.time_zone) 110 | 111 | -------------------------------------------------------------------------------- /zmanim/hebrew_calendar/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pinnymz/python-zmanim/d33b8fe499de36a696e07662197a76ebcb5ee89e/zmanim/hebrew_calendar/__init__.py -------------------------------------------------------------------------------- /zmanim/hebrew_calendar/jewish_calendar.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime, timedelta 2 | from enum import Enum 3 | from typing import Optional 4 | 5 | from dateutil import tz 6 | 7 | from zmanim.hebrew_calendar.jewish_date import JewishDate 8 | from zmanim.util.geo_location import GeoLocation 9 | 10 | 11 | class JewishCalendar(JewishDate): 12 | SIGNIFICANT_DAYS = Enum('SignificantDays', 'erev_rosh_hashana rosh_hashana tzom_gedalyah erev_yom_kippur yom_kippur \ 13 | erev_succos succos chol_hamoed_succos hoshana_rabbah shemini_atzeres simchas_torah \ 14 | chanukah tenth_of_teves tu_beshvat \ 15 | taanis_esther purim shushan_purim purim_katan shushan_purim_katan \ 16 | erev_pesach pesach chol_hamoed_pesach pesach_sheni lag_baomer erev_shavuos shavuos \ 17 | seventeen_of_tammuz tisha_beav tu_beav \ 18 | yom_hashoah yom_hazikaron yom_haatzmaut yom_yerushalayim') 19 | 20 | def __init__(self, *args, **kwargs): 21 | in_israel = None 22 | if 'in_israel' in kwargs: 23 | in_israel = kwargs.pop('in_israel') 24 | if len(args) == 4: 25 | super(JewishCalendar, self).__init__(*args[:3], **kwargs) 26 | in_israel = args[3] 27 | else: 28 | super(JewishCalendar, self).__init__(*args, **kwargs) 29 | self.in_israel = False if in_israel is None else in_israel 30 | self.use_modern_holidays = False 31 | 32 | def __repr__(self): 33 | return "<%s in_israel=%r, gregorian_date=%r, jewish_date=%r, day_of_week=%r, molad_hours=%r, molad_minutes=%r, molad_chalakim=%r>" % \ 34 | (self.__module__ + "." + self.__class__.__qualname__, self.in_israel, self.gregorian_date, 35 | self.jewish_date, self.day_of_week, self.molad_hours, self.molad_minutes, self.molad_chalakim) 36 | 37 | def significant_day(self) -> Optional[str]: 38 | return getattr(self, f'_{self.jewish_month_name()}_significant_day', None)() 39 | 40 | def significant_shabbos(self) -> Optional[str]: 41 | if self.day_of_week != 7: 42 | return None 43 | if self.jewish_month == 1: 44 | if self.jewish_day == 1: 45 | return 'parshas_hachodesh' 46 | elif self.jewish_day in range(8, 15): 47 | return 'shabbos_hagadol' 48 | elif self.jewish_month == 7 and self.jewish_day in range(3, 10): 49 | return 'shabbos_shuva' 50 | elif self.jewish_month == (self.months_in_jewish_year() - 1) and self.jewish_day in range(25, 31): 51 | return 'parshas_shekalim' 52 | elif self.jewish_month == self.months_in_jewish_year(): 53 | if self.jewish_day == 1: 54 | return 'parshas_shekalim' 55 | elif self.jewish_day in range(7, 14): 56 | return 'parshas_zachor' 57 | elif self.jewish_day in range(17, 24): 58 | return 'parshas_parah' 59 | elif self.jewish_day in range(24, 30): 60 | return 'parshas_hachodesh' 61 | 62 | def is_assur_bemelacha(self) -> bool: 63 | return self.day_of_week == 7 or self.is_yom_tov_assur_bemelacha() 64 | 65 | def is_tomorrow_assur_bemelacha(self) -> bool: 66 | return self.day_of_week == 6 or self.is_erev_yom_tov() or self.is_erev_yom_tov_sheni() 67 | 68 | def has_candle_lighting(self) -> bool: 69 | return self.is_tomorrow_assur_bemelacha() 70 | 71 | def has_delayed_candle_lighting(self) -> bool: 72 | return self.day_of_week != 6 and self.has_candle_lighting() and self.is_assur_bemelacha() 73 | 74 | def is_yom_tov(self) -> bool: 75 | sd = self.significant_day() 76 | return sd is not None \ 77 | and not sd.startswith('erev_') \ 78 | and (not self.is_taanis() or sd == 'yom_kippur') 79 | 80 | def is_yom_tov_assur_bemelacha(self) -> bool: 81 | return self.significant_day() in ['pesach', 'shavuos', 'rosh_hashana', 'yom_kippur', 82 | 'succos', 'shemini_atzeres', 'simchas_torah'] 83 | 84 | def is_erev_yom_tov(self) -> bool: 85 | sd = self.significant_day() 86 | return sd is not None and (sd.startswith('erev_') 87 | or sd == 'hoshana_rabbah' 88 | or (sd == 'chol_hamoed_pesach' and self.jewish_day == 20)) 89 | 90 | def is_yom_tov_sheni(self) -> bool: 91 | return ((self.jewish_month == 7 and self.jewish_day == 2) 92 | or (not self.in_israel and ( 93 | (self.jewish_month == 7 and self.jewish_day in [16, 23]) or 94 | (self.jewish_month == 1 and self.jewish_day in [16, 22]) or 95 | (self.jewish_month == 3 and self.jewish_day == 7) 96 | ))) 97 | 98 | def is_erev_yom_tov_sheni(self) -> bool: 99 | return ((self.jewish_month == 7 and self.jewish_day == 1) 100 | or (not self.in_israel and ( 101 | (self.jewish_month == 7 and self.jewish_day in [15, 22]) or 102 | (self.jewish_month == 1 and self.jewish_day in [15, 21]) or 103 | (self.jewish_month == 3 and self.jewish_day == 6) 104 | ))) 105 | 106 | def is_chol_hamoed(self) -> bool: 107 | sd = self.significant_day() 108 | return sd is not None and (sd.startswith('chol_hamoed_') or sd == 'hoshana_rabbah') 109 | 110 | def is_taanis(self) -> bool: 111 | return self.significant_day() in ['seventeen_of_tammuz', 'tisha_beav', 'tzom_gedalyah', 112 | 'yom_kippur', 'tenth_of_teves', 'taanis_esther'] 113 | 114 | def is_taanis_bechorim(self) -> bool: 115 | return ((self.day_of_week != 7 and self.jewish_day == 14 and self.jewish_month == 1) or 116 | (self.day_of_week == 5 and self.jewish_day == 12 and self.jewish_month == 1)) 117 | 118 | def is_shabbos_mevorchim(self) -> bool: 119 | return self.day_of_week == 7 and self.jewish_month != 6 and self.jewish_day in range(23, 30) 120 | 121 | def is_rosh_chodesh(self) -> bool: 122 | return self.jewish_day == 30 or (self.jewish_day == 1 and self.jewish_month != 7) 123 | 124 | def is_erev_rosh_chodesh(self) -> bool: 125 | return self.jewish_day == 29 and self.jewish_month != 6 126 | 127 | def is_chanukah(self) -> bool: 128 | return self.significant_day() == 'chanukah' 129 | 130 | def day_of_chanukah(self) -> Optional[int]: 131 | if not self.is_chanukah(): 132 | return None 133 | 134 | if self.jewish_month_name() == 'kislev': 135 | return self.jewish_day - 24 136 | else: 137 | return self.jewish_day + (5 if self.is_kislev_short() else 6) 138 | 139 | def day_of_omer(self) -> Optional[int]: 140 | month_name = self.jewish_month_name() 141 | if month_name == 'nissan': 142 | return self.jewish_day - 15 if self.jewish_day > 15 else None 143 | elif month_name == 'iyar': 144 | return self.jewish_day + 15 145 | elif month_name == 'sivan': 146 | return self.jewish_day + 44 if self.jewish_day < 6 else None 147 | else: 148 | return None 149 | 150 | def molad_as_datetime(self) -> datetime: 151 | m = self.molad() 152 | location_name = 'Jerusalem, Israel' 153 | latitude = 31.778 # Har Habayis latitude 154 | longitude = 35.2354 # Har Habayis longitude 155 | zone = tz.gettz('Asia/Jerusalem') 156 | 157 | geo = GeoLocation(location_name, latitude, longitude, zone) 158 | seconds = m.molad_chalakim * 10 / 3.0 159 | seconds, microseconds = divmod(seconds * 10**6, 10**6) 160 | # molad as local mean time 161 | time = datetime(m.gregorian_year, m.gregorian_month, m.gregorian_day, 162 | m.molad_hours, m.molad_minutes, int(seconds), int(microseconds), 163 | tzinfo=tz.gettz('Etc/GMT-2')) 164 | # molad as Jerusalem standard time 165 | micro_offset = geo.local_mean_time_offset() * 1000 166 | time -= timedelta(microseconds=micro_offset) 167 | # molad as UTC 168 | return time.astimezone(tz.UTC) 169 | 170 | def techilas_zman_kiddush_levana_3_days(self) -> datetime: 171 | return self.molad_as_datetime() + timedelta(3) 172 | 173 | def techilas_zman_kiddush_levana_7_days(self) -> datetime: 174 | return self.molad_as_datetime() + timedelta(7) 175 | 176 | def sof_zman_kiddush_levana_between_moldos(self) -> datetime: 177 | half_molad_in_seconds = self.CHALAKIM_PER_MONTH * 10 / 6.0 178 | return self.molad_as_datetime() + timedelta(microseconds=half_molad_in_seconds * 10**6) 179 | 180 | def sof_zman_kiddush_levana_15_days(self) -> datetime: 181 | return self.molad_as_datetime() + timedelta(15) 182 | 183 | def _nissan_significant_day(self) -> Optional[str]: 184 | pesach = [15, 21] 185 | if not self.in_israel: 186 | pesach += [16, 22] 187 | 188 | if self.jewish_day == 14: 189 | return 'erev_pesach' 190 | elif self.jewish_day in pesach: 191 | return 'pesach' 192 | elif self.jewish_day in range(16,21): 193 | return 'chol_hamoed_pesach' 194 | elif self.use_modern_holidays: 195 | if (self.jewish_day == 26 and self.day_of_week == 5) \ 196 | or (self.jewish_day == 27 and self.day_of_week not in [1, 6]) \ 197 | or (self.jewish_day == 28 and self.day_of_week == 2): 198 | return 'yom_hashoah' 199 | 200 | def _iyar_significant_day(self) -> Optional[str]: 201 | if self.jewish_day == 14: 202 | return 'pesach_sheni' 203 | elif self.jewish_day == 18: 204 | return 'lag_baomer' 205 | elif self.use_modern_holidays: 206 | # Note that this logic follows the current rules, which were last revised in 5764. 207 | # The calculations for years prior may not reflect the actual dates observed at that time. 208 | if (self.jewish_day in [2, 3] and self.day_of_week == 4) \ 209 | or (self.jewish_day == 4 and self.day_of_week == 3) \ 210 | or (self.jewish_day == 5 and self.day_of_week == 2): 211 | return 'yom_hazikaron' 212 | elif (self.jewish_day in [3, 4] and self.day_of_week == 5) \ 213 | or (self.jewish_day == 5 and self.day_of_week == 4) \ 214 | or (self.jewish_day == 6 and self.day_of_week == 3): 215 | return 'yom_haatzmaut' 216 | elif self.jewish_day == 28: 217 | return 'yom_yerushalayim' 218 | 219 | def _sivan_significant_day(self) -> Optional[str]: 220 | shavuos = [6] 221 | if not self.in_israel: 222 | shavuos += [7] 223 | 224 | if self.jewish_day == 5: 225 | return 'erev_shavuos' 226 | elif self.jewish_day in shavuos: 227 | return 'shavuos' 228 | 229 | def _tammuz_significant_day(self) -> Optional[str]: 230 | if (self.jewish_day == 17 and self.day_of_week != 7) \ 231 | or (self.jewish_day == 18 and self.day_of_week == 1): 232 | return 'seventeen_of_tammuz' 233 | 234 | def _av_significant_day(self) -> Optional[str]: 235 | if (self.jewish_day == 9 and self.day_of_week != 7) \ 236 | or (self.jewish_day == 10 and self.day_of_week == 1): 237 | return 'tisha_beav' 238 | elif self.jewish_day == 15: 239 | return 'tu_beav' 240 | 241 | def _elul_significant_day(self) -> Optional[str]: 242 | if self.jewish_day == 29: 243 | return 'erev_rosh_hashana' 244 | 245 | def _tishrei_significant_day(self) -> Optional[str]: 246 | succos = [15] 247 | if not self.in_israel: 248 | succos += [16] 249 | 250 | if self.jewish_day in [1, 2]: 251 | return 'rosh_hashana' 252 | elif (self.jewish_day == 3 and self.day_of_week != 7) \ 253 | or (self.jewish_day == 4 and self.day_of_week == 1): 254 | return 'tzom_gedalyah' 255 | elif self.jewish_day == 9: 256 | return 'erev_yom_kippur' 257 | elif self.jewish_day == 10: 258 | return 'yom_kippur' 259 | elif self.jewish_day == 14: 260 | return 'erev_succos' 261 | elif self.jewish_day in succos: 262 | return 'succos' 263 | elif self.jewish_day in range(16,21): 264 | return 'chol_hamoed_succos' 265 | elif self.jewish_day == 21: 266 | return 'hoshana_rabbah' 267 | elif self.jewish_day == 22: 268 | return 'shemini_atzeres' 269 | elif self.jewish_day == 23 and not self.in_israel: 270 | return 'simchas_torah' 271 | 272 | def _cheshvan_significant_day(self) -> None: 273 | return None 274 | 275 | def _kislev_significant_day(self) -> Optional[str]: 276 | if self.jewish_day >= 25: 277 | return 'chanukah' 278 | 279 | def _teves_significant_day(self) -> Optional[str]: 280 | chanukah = [1,2] 281 | if self.is_kislev_short(): 282 | chanukah += [3] 283 | 284 | if self.jewish_day in chanukah: 285 | return 'chanukah' 286 | elif self.jewish_day == 10: 287 | return 'tenth_of_teves' 288 | 289 | def _shevat_significant_day(self) -> Optional[str]: 290 | if self.jewish_day == 15: 291 | return 'tu_beshvat' 292 | 293 | def _adar_significant_day(self) -> Optional[str]: 294 | if self.is_jewish_leap_year(): 295 | if self.jewish_day == 14: 296 | return 'purim_katan' 297 | elif self.jewish_day == 15: 298 | return 'shushan_purim_katan' 299 | else: 300 | return self._purim_significant_day() 301 | 302 | def _adar_ii_significant_day(self) -> Optional[str]: 303 | return self._purim_significant_day() 304 | 305 | def _purim_significant_day(self) -> Optional[str]: 306 | if (self.jewish_day == 13 and self.day_of_week != 7) \ 307 | or (self.jewish_day == 11 and self.day_of_week == 5): 308 | return 'taanis_esther' 309 | elif self.jewish_day == 14: 310 | return 'purim' 311 | elif self.jewish_day == 15: 312 | return 'shushan_purim' -------------------------------------------------------------------------------- /zmanim/hebrew_calendar/jewish_date.py: -------------------------------------------------------------------------------- 1 | import copy 2 | from datetime import date, timedelta 3 | from enum import Enum 4 | from memoization import cached 5 | from typing import Optional 6 | 7 | 8 | class JewishDate: 9 | MONTHS = Enum('Months', 'nissan iyar sivan tammuz av elul tishrei cheshvan kislev teves shevat adar adar_ii') 10 | MONTHS_LIST = list(MONTHS) 11 | 12 | RD = date(1, 1, 1) 13 | JEWISH_EPOCH = -1373429 14 | 15 | CHALAKIM_PER_MINUTE = 18 16 | CHALAKIM_PER_HOUR = CHALAKIM_PER_MINUTE * 60 17 | CHALAKIM_PER_DAY = CHALAKIM_PER_HOUR * 24 18 | CHALAKIM_PER_MONTH = int(CHALAKIM_PER_DAY * 29.5) + 793 19 | 20 | CHALAKIM_MOLAD_TOHU = CHALAKIM_PER_DAY + (CHALAKIM_PER_HOUR * 5) + 204 21 | 22 | CHESHVAN_KISLEV_KEVIAH = Enum('Kviah', 'chaseirim kesidran shelaimim') 23 | 24 | def __init__(self, *args, **kwargs): 25 | if len(args) == 0: 26 | self.reset_date() 27 | elif len(args) == 3: 28 | self.set_jewish_date(*args, **kwargs) 29 | elif len(args) == 1 and isinstance(args[0], date): 30 | self.date = args[0] 31 | elif len(args) == 1 and isinstance(args[0], int): 32 | self._set_from_molad(*args) 33 | else: 34 | raise ValueError("invalid arguments for new JewishDate") 35 | 36 | def __repr__(self): 37 | return "<%s gregorian_date=%r, jewish_date=%r, day_of_week=%r, molad_hours=%r, molad_minutes=%r, molad_chalakim=%r>" % \ 38 | (self.__module__ + "." + self.__class__.__qualname__, self.gregorian_date, 39 | self.jewish_date, self.day_of_week, self.molad_hours, self.molad_minutes, self.molad_chalakim) 40 | 41 | @property 42 | def gregorian_date(self) -> date: 43 | return self.__gregorian_date 44 | 45 | @property 46 | def gregorian_year(self) -> int: 47 | return self.gregorian_date.year 48 | 49 | @gregorian_year.setter 50 | def gregorian_year(self, year: int): 51 | self.set_gregorian_date(year, self.gregorian_month, self.gregorian_day) 52 | 53 | @property 54 | def gregorian_month(self) -> int: 55 | return self.gregorian_date.month 56 | 57 | @gregorian_month.setter 58 | def gregorian_month(self, month: int): 59 | self.set_gregorian_date(self.gregorian_year, month, self.gregorian_day) 60 | 61 | @property 62 | def gregorian_day(self) -> int: 63 | return self.gregorian_date.day 64 | 65 | @gregorian_day.setter 66 | def gregorian_day(self, day: int): 67 | self.set_gregorian_date(self.gregorian_year, self.gregorian_month, day) 68 | 69 | @property 70 | def day_of_week(self) -> int: 71 | return self.__day_of_week 72 | 73 | @property 74 | def jewish_date(self) -> (int, int, int): 75 | return self.__jewish_year, self.__jewish_month, self.__jewish_day 76 | 77 | @property 78 | def jewish_year(self) -> int: 79 | return self.__jewish_year 80 | 81 | @jewish_year.setter 82 | def jewish_year(self, year: int): 83 | self.set_jewish_date(year, self.jewish_month, self.jewish_day) 84 | 85 | @property 86 | def jewish_month(self) -> int: 87 | return self.__jewish_month 88 | 89 | @jewish_month.setter 90 | def jewish_month(self, month: int): 91 | self.set_jewish_date(self.jewish_year, month, self.jewish_day) 92 | 93 | @property 94 | def jewish_day(self) -> int: 95 | return self.__jewish_day 96 | 97 | @jewish_day.setter 98 | def jewish_day(self, day: int): 99 | self.set_jewish_date(self.jewish_year, self.jewish_month, day) 100 | 101 | @property 102 | def molad_hours(self) -> int: 103 | return self.__molad_hours 104 | 105 | @property 106 | def molad_minutes(self) -> int: 107 | return self.__molad_minutes 108 | 109 | @property 110 | def molad_chalakim(self) -> int: 111 | return self.__molad_chalakim 112 | 113 | def __date(self, gregorian_date): 114 | self.__gregorian_date = gregorian_date 115 | self.__absolute_date = self._gregorian_date_to_abs_date(gregorian_date) 116 | self._reset_day_of_week() 117 | self.__molad_hours = self.__molad_minutes = self.__molad_chalakim = 0 118 | jewish_year, jewish_month, jewish_day = self._jewish_date_from_abs_date(self.__absolute_date) 119 | self.__jewish_year = jewish_year 120 | self.__jewish_month = jewish_month 121 | self.__jewish_day = jewish_day 122 | 123 | date = property(fset=__date) 124 | 125 | @classmethod 126 | def from_molad(cls, molad: int) -> 'JewishDate': 127 | return cls(molad) 128 | 129 | @classmethod 130 | def from_jewish_date(cls, year: int, month: int, date: int) -> 'JewishDate': 131 | return cls(year, month, date) 132 | 133 | @classmethod 134 | def from_date(cls, date: date) -> 'JewishDate': 135 | return cls(date) 136 | 137 | def reset_date(self) -> 'JewishDate': 138 | self.date = date.today() 139 | return self 140 | 141 | def set_jewish_date(self, year: int, month: int, day: int, hours: int = 0, minutes: int = 0, chalakim: int = 0): 142 | if year < 1 or month < 1 or month > 13 or day < 1 or day > 30 \ 143 | or hours < 0 or hours > 23 or minutes < 0 or minutes > 59 or chalakim < 0 or chalakim > 17: 144 | raise ValueError("invalid date parts") 145 | max_months = self.months_in_jewish_year(year) 146 | month = max_months if month > max_months else month 147 | max_days = self.days_in_jewish_month(month, year) 148 | day = max_days if day > max_days else day 149 | abs_date = self._jewish_date_to_abs_date(year, month, day) 150 | if abs_date < 0: 151 | raise ValueError("unsupported early date") 152 | self.date = self._gregorian_date_from_abs_date(abs_date) 153 | self.__molad_hours = hours 154 | self.__molad_minutes = minutes 155 | self.__molad_chalakim = chalakim 156 | 157 | def set_gregorian_date(self, year: int, month: int, day: int): 158 | if year < 1 or month < 1 or month > 12 or day < 1 or day > 31: 159 | raise ValueError("invalid date parts") 160 | max_days = self.days_in_gregorian_month(month, year) 161 | day = max_days if day > max_days else day 162 | self.date = date(year, month, day) 163 | 164 | def forward(self, increment: int = 1) -> 'JewishDate': 165 | if increment < 0: 166 | return self.back(-increment) 167 | if increment > 500: 168 | self.date = self.gregorian_date + timedelta(days=increment) 169 | return self 170 | days_of_year = self.sorted_days_in_jewish_year() 171 | y, m, d = self.jewish_year, self.jewish_month, self.jewish_day 172 | d += increment 173 | 174 | def find_days_in_month(month, doy) -> int: 175 | return next(pair[1] for pair in doy if pair[0] == month) 176 | 177 | days_in_month = find_days_in_month(m, days_of_year) 178 | while d > days_in_month: 179 | d -= days_in_month 180 | m += 1 181 | if m > len(days_of_year): 182 | m = 1 183 | if m == 7: 184 | y += 1 185 | days_of_year = self.sorted_days_in_jewish_year(y) 186 | days_in_month = find_days_in_month(m, days_of_year) 187 | 188 | self.__gregorian_date += timedelta(days=increment) 189 | self.__absolute_date += increment 190 | self._reset_day_of_week() 191 | self.__jewish_year = y 192 | self.__jewish_month = m 193 | self.__jewish_day = d 194 | return self 195 | 196 | def back(self, decrement: int = 1) -> 'JewishDate': 197 | if decrement < 0: 198 | return self.forward(-decrement) 199 | if decrement > 500: 200 | self.date = self.gregorian_date - timedelta(days=decrement) 201 | return self 202 | days_of_year = self.sorted_days_in_jewish_year() 203 | y, m, d = self.jewish_year, self.jewish_month, self.jewish_day 204 | d -= decrement 205 | 206 | def find_days_in_month(month, doy) -> int: 207 | return next(pair[1] for pair in doy if pair[0] == month) 208 | 209 | while d <= 0: 210 | m -= 1 211 | if m == 0: 212 | m = len(days_of_year) 213 | if m == 6: 214 | y -= 1 215 | days_of_year = self.sorted_days_in_jewish_year(y) 216 | d += find_days_in_month(m, days_of_year) 217 | 218 | self.__gregorian_date -= timedelta(days=decrement) 219 | self.__absolute_date -= decrement 220 | self._reset_day_of_week() 221 | self.__jewish_year = y 222 | self.__jewish_month = m 223 | self.__jewish_day = d 224 | return self 225 | 226 | def __add__(self, addend) -> 'JewishDate': 227 | if isinstance(addend, int): 228 | return copy.copy(self).forward(addend) 229 | elif isinstance(addend, timedelta): 230 | return type(self)(self.gregorian_date + addend) 231 | raise ValueError 232 | 233 | def __sub__(self, subtrahend): 234 | if isinstance(subtrahend, int): 235 | return copy.copy(self).back(subtrahend) 236 | elif isinstance(subtrahend, timedelta): 237 | return type(self)(self.gregorian_date - subtrahend) 238 | elif isinstance(subtrahend, JewishDate): 239 | return self.gregorian_date - subtrahend.gregorian_date 240 | elif isinstance(subtrahend, date): 241 | return self.gregorian_date - subtrahend 242 | raise ValueError 243 | 244 | def __eq__(self, other): 245 | if isinstance(other, JewishDate): 246 | return self.gregorian_date == other.gregorian_date 247 | else: 248 | return self.gregorian_date == other 249 | 250 | def __ne__(self, other): 251 | if isinstance(other, JewishDate): 252 | return self.gregorian_date != other.gregorian_date 253 | else: 254 | return self.gregorian_date != other 255 | 256 | def __lt__(self, other): 257 | if isinstance(other, JewishDate): 258 | return self.gregorian_date < other.gregorian_date 259 | else: 260 | return self.gregorian_date < other 261 | 262 | def __le__(self, other): 263 | if isinstance(other, JewishDate): 264 | return self.gregorian_date <= other.gregorian_date 265 | else: 266 | return self.gregorian_date <= other 267 | 268 | def __gt__(self, other): 269 | if isinstance(other, JewishDate): 270 | return self.gregorian_date > other.gregorian_date 271 | else: 272 | return self.gregorian_date > other 273 | 274 | def __ge__(self, other): 275 | if isinstance(other, JewishDate): 276 | return self.gregorian_date >= other.gregorian_date 277 | else: 278 | return self.gregorian_date >= other 279 | 280 | def days_in_gregorian_year(self, year: Optional[int] = None) -> int: 281 | if year is None: 282 | year = self.gregorian_year 283 | return 366 if self.is_gregorian_leap_year(year) else 365 284 | 285 | def days_in_gregorian_month(self, month: Optional[int] = None, year: Optional[int] = None) -> int: 286 | if month is None: 287 | month = self.gregorian_month 288 | if year is None: 289 | year = self.gregorian_year 290 | if month == 2: 291 | return 29 if self.is_gregorian_leap_year(year) else 28 292 | elif month in [4, 6, 9, 11]: 293 | return 30 294 | else: 295 | return 31 296 | 297 | def is_gregorian_leap_year(self, year: Optional[int] = None) -> bool: 298 | if year is None: 299 | year = self.gregorian_year 300 | return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0) 301 | 302 | def months_in_jewish_year(self, year: Optional[int] = None) -> int: 303 | if year is None: 304 | year = self.jewish_year 305 | return self._months_in_jewish_year(year) 306 | 307 | # Returns the list of jewish months for a given jewish year in chronological order 308 | # sorted_months_in_jewish_year(5779) 309 | # => [7, 8, 9, 10, 11, 12, 13, 1, 2, 3, 4, 5, 6] 310 | def sorted_months_in_jewish_year(self, year: Optional[int] = None) -> list: 311 | if year is None: 312 | year = self.jewish_year 313 | return self._sorted_months_in_jewish_year(year) 314 | 315 | # Returns the number of days in each jewish month for a given jewish year in chronological order 316 | # sorted_days_in_jewish_year(5779) 317 | # => [(7, 30), (8, 29), (9, 30), (10, 29), (11, 30), (12, 30), (13, 29), (1, 30), (2, 29), (3, 30), (4, 29), (5, 30), (6, 29)] 318 | def sorted_days_in_jewish_year(self, year: Optional[int] = None) -> list: 319 | if year is None: 320 | year = self.jewish_year 321 | return self._sorted_days_in_jewish_year(year) 322 | 323 | def days_in_jewish_year(self, year: Optional[int] = None) -> int: 324 | if year is None: 325 | year = self.jewish_year 326 | return self._days_in_jewish_year(year) 327 | 328 | def days_in_jewish_month(self, month: Optional[int] = None, year: Optional[int] = None) -> int: 329 | if month is None: 330 | month = self.jewish_month 331 | if year is None: 332 | year = self.jewish_year 333 | if month < 1 or month > self.months_in_jewish_year(year): 334 | raise ValueError("invalid month number") 335 | return self._days_in_jewish_month(month, year) 336 | 337 | def day_number_of_jewish_year(self, year: Optional[int] = None, month: Optional[int] = None, day: Optional[int] = None) -> int: 338 | if year is None: 339 | year = self.jewish_year 340 | if month is None: 341 | month = self.jewish_month 342 | if day is None: 343 | day = self.jewish_day 344 | month_index = self._month_number_from_tishrei(year, month) - 1 345 | prior_months = self.sorted_months_in_jewish_year(year)[:month_index] 346 | return day + sum(self.days_in_jewish_month(m, year) for m in prior_months) 347 | 348 | def is_cheshvan_long(self, year: Optional[int] = None) -> bool: 349 | if year is None: 350 | year = self.jewish_year 351 | return self._is_cheshvan_long(year) 352 | 353 | def is_cheshvan_short(self, year: Optional[int] = None) -> bool: 354 | return not self.is_cheshvan_long(year) 355 | 356 | def is_kislev_long(self, year: Optional[int] = None) -> bool: 357 | return not self.is_kislev_short(year) 358 | 359 | def is_kislev_short(self, year: Optional[int] = None) -> bool: 360 | if year is None: 361 | year = self.jewish_year 362 | return self._is_kislev_short(year) 363 | 364 | def is_jewish_leap_year(self, year: Optional[int] = None) -> bool: 365 | if year is None: 366 | year = self.jewish_year 367 | return self._is_jewish_leap_year(year) 368 | 369 | def cheshvan_kislev_kviah(self, year: Optional[int] = None) -> str: 370 | if year is None: 371 | year = self.jewish_year 372 | year_type = (self.days_in_jewish_year(year) % 10) - 3 373 | return list(self.CHESHVAN_KISLEV_KEVIAH)[year_type] 374 | 375 | def kviah(self, year: Optional[int] = None) -> tuple: 376 | if year is None: 377 | year = self.jewish_year 378 | date = JewishDate(year, 7, 1) 379 | kviah_value = date.cheshvan_kislev_kviah() 380 | rosh_hashana_day = date.day_of_week 381 | date.jewish_month = 1 382 | pesach_day = date.day_of_week 383 | return rosh_hashana_day, kviah_value, pesach_day 384 | 385 | def molad(self, month: int = None, year: Optional[int] = None) -> 'JewishDate': 386 | if month is None: 387 | month = self.jewish_month 388 | if year is None: 389 | year = self.jewish_year 390 | return self.from_molad(self._chalakim_since_molad_tohu(year, month)) 391 | 392 | def jewish_month_name(self, month: Optional[int] = None) -> str: 393 | if month is None: 394 | month = self.jewish_month 395 | return self._jewish_month_name(month) 396 | 397 | def jewish_month_from_name(self, month_name: str) -> int: 398 | return next(m.value for m in self.MONTHS if m.name == month_name) 399 | 400 | def _set_from_molad(self, molad: int): 401 | gregorian_date = self._gregorian_date_from_abs_date(self._molad_to_abs_date(molad)) 402 | remainder = molad % self.CHALAKIM_PER_DAY 403 | molad_hours, remainder = divmod(remainder, self.CHALAKIM_PER_HOUR) 404 | # molad hours start at 18:00, which means that 405 | # we cross a secular date boundary if hours are 6 or greater 406 | if molad_hours >= 6: 407 | gregorian_date += timedelta(days=1) 408 | self.date = gregorian_date 409 | # Normalize hours to start at 00:00 410 | self.__molad_hours = (molad_hours + 18) % 24 411 | minutes, chalakim = divmod(remainder, self.CHALAKIM_PER_MINUTE) 412 | self.__molad_minutes = minutes 413 | self.__molad_chalakim = chalakim 414 | 415 | def _jewish_year_start_to_abs_date(self, year: int) -> int: 416 | return self._jewish_calendar_elapsed_days(year) + self.JEWISH_EPOCH + 1 417 | 418 | def _jewish_date_to_abs_date(self, year: int, month: int, day: int) -> int: 419 | return self.day_number_of_jewish_year(year, month, day) + \ 420 | self._jewish_year_start_to_abs_date(year) - 1 421 | 422 | def _jewish_date_from_abs_date(self, absolute_date: int) -> (int, int, int): 423 | jewish_year = int((absolute_date - self.JEWISH_EPOCH) / 366) 424 | 425 | # estimate may be low for CE 426 | while absolute_date >= self._jewish_year_start_to_abs_date(jewish_year + 1): 427 | jewish_year += 1 428 | 429 | # estimate may be high for BCE 430 | while absolute_date < self._jewish_year_start_to_abs_date(jewish_year): 431 | jewish_year -= 1 432 | 433 | months = self.sorted_months_in_jewish_year(jewish_year) 434 | jewish_month = next((m for i, m in enumerate(months[:len(months)-1]) if absolute_date < self._jewish_date_to_abs_date(jewish_year, months[i + 1], 1)), months[len(months) - 1]) 435 | 436 | jewish_day = absolute_date - self._jewish_date_to_abs_date(jewish_year, jewish_month, 1) + 1 437 | 438 | return jewish_year, jewish_month, jewish_day 439 | 440 | def _gregorian_date_to_abs_date(self, gregorian_date: date) -> int: 441 | return gregorian_date.toordinal() 442 | 443 | def _gregorian_date_from_abs_date(self, absolute_date: int) -> date: 444 | return date.fromordinal(absolute_date) 445 | 446 | def _molad_to_abs_date(self, chalakim: int) -> int: 447 | return int(chalakim / self.CHALAKIM_PER_DAY) + self.JEWISH_EPOCH 448 | 449 | def _reset_day_of_week(self): 450 | self.__day_of_week = (self.gregorian_date.isoweekday() % 7) + 1 451 | 452 | @staticmethod 453 | def _jewish_month_name(month: int) -> str: 454 | return JewishDate.MONTHS_LIST[month - 1].name 455 | 456 | @staticmethod 457 | def _is_jewish_leap_year(year: int) -> bool: 458 | return ((7 * year) + 1) % 19 < 7 459 | 460 | @staticmethod 461 | def _is_cheshvan_long(year: int) -> bool: 462 | return JewishDate._days_in_jewish_year(year) % 10 == 5 463 | 464 | @staticmethod 465 | def _is_kislev_short(year: int) -> bool: 466 | return JewishDate._days_in_jewish_year(year) % 10 == 3 467 | 468 | @staticmethod 469 | def _months_in_jewish_year(year: int) -> int: 470 | return 13 if JewishDate._is_jewish_leap_year(year) else 12 471 | 472 | @staticmethod 473 | @cached(ttl=30) 474 | def _days_in_jewish_month(month: int, year: int) -> int: 475 | m = JewishDate._jewish_month_name(month) 476 | if (m in ('iyar', 'tammuz', 'elul', 'teves', 'adar_ii')) or \ 477 | (m == 'cheshvan' and not JewishDate._is_cheshvan_long(year)) or \ 478 | (m == 'kislev' and JewishDate._is_kislev_short(year)) or \ 479 | (m == 'adar' and not JewishDate._is_jewish_leap_year(year)): 480 | return 29 481 | return 30 482 | 483 | @staticmethod 484 | @cached(ttl=30) 485 | def _days_in_jewish_year(year: int) -> int: 486 | return JewishDate._jewish_calendar_elapsed_days(year + 1) - JewishDate._jewish_calendar_elapsed_days(year) 487 | 488 | @staticmethod 489 | @cached(ttl=30) 490 | def _sorted_months_in_jewish_year(year: int) -> list: 491 | return sorted(range(1, JewishDate._months_in_jewish_year(year) + 1), key=lambda y: (0 if y >= 7 else 1, y)) 492 | 493 | @staticmethod 494 | @cached(ttl=30) 495 | def _sorted_days_in_jewish_year(year: int) -> list: 496 | return list(map(lambda month: (month, JewishDate._days_in_jewish_month(month, year)), 497 | JewishDate._sorted_months_in_jewish_year(year))) 498 | 499 | @staticmethod 500 | def _jewish_calendar_elapsed_days(year: int) -> int: 501 | days, remainder = JewishDate._molad_components_for_year(year) 502 | return days + JewishDate._dechiyos_count(year, days, remainder) 503 | 504 | @staticmethod 505 | def _dechiyos_count(year: int, days: int, remainder: int) -> int: 506 | count = 0 507 | # 'days' is Monday-based due to start of Molad at BaHaRaD 508 | # add 1 to convert to Sunday-based, '0' represents Shabbos 509 | rosh_hashana_day = (days + 1) % 7 510 | if (remainder >= 19440) or \ 511 | ((rosh_hashana_day == 3) and (remainder >= 9924) and not JewishDate._is_jewish_leap_year(year)) or \ 512 | ((rosh_hashana_day == 2) and (remainder >= 16789) and JewishDate._is_jewish_leap_year(year-1)): 513 | count = 1 514 | if ((rosh_hashana_day + count) % 7) in [1, 4, 6]: 515 | count += 1 516 | return count 517 | 518 | @staticmethod 519 | def _molad_components_for_year(year: int) -> (int, int): 520 | chalakim = JewishDate._chalakim_since_molad_tohu(year, 7) # chalakim up to tishrei of given year 521 | days, remainder = divmod(chalakim, JewishDate.CHALAKIM_PER_DAY) 522 | return int(days), int(remainder) 523 | 524 | @staticmethod 525 | def _chalakim_since_molad_tohu(year: int, month: int) -> int: 526 | prev_year = year - 1 527 | months = JewishDate._month_number_from_tishrei(year, month) - 1 528 | cycles, remainder = divmod(prev_year, 19) 529 | months += int(235 * cycles) + \ 530 | int(12 * remainder) + \ 531 | int(((7 * remainder) + 1) / 19) 532 | 533 | return JewishDate.CHALAKIM_MOLAD_TOHU + (JewishDate.CHALAKIM_PER_MONTH * months) 534 | 535 | @staticmethod 536 | def _month_number_from_tishrei(year: int, month: int) -> int: 537 | leap = JewishDate._is_jewish_leap_year(year) 538 | return 1 + ((month + (6 if leap else 5)) % (13 if leap else 12)) 539 | -------------------------------------------------------------------------------- /zmanim/limudim/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pinnymz/python-zmanim/d33b8fe499de36a696e07662197a76ebcb5ee89e/zmanim/limudim/__init__.py -------------------------------------------------------------------------------- /zmanim/limudim/anchor.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | from zmanim.hebrew_calendar.jewish_date import JewishDate 4 | 5 | 6 | class Anchor: 7 | def next_occurrence(self, jewish_date: JewishDate) -> Optional[JewishDate]: 8 | raise NotImplementedError 9 | 10 | def previous_occurrence(self, jewish_date: JewishDate) -> Optional[JewishDate]: 11 | raise NotImplementedError 12 | 13 | def current_or_previous_occurrence(self, jewish_date: JewishDate) -> Optional[JewishDate]: 14 | raise NotImplementedError 15 | -------------------------------------------------------------------------------- /zmanim/limudim/anchors/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pinnymz/python-zmanim/d33b8fe499de36a696e07662197a76ebcb5ee89e/zmanim/limudim/anchors/__init__.py -------------------------------------------------------------------------------- /zmanim/limudim/anchors/day_of_month_anchor.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | from zmanim.hebrew_calendar.jewish_date import JewishDate 4 | from zmanim.limudim.anchor import Anchor 5 | 6 | 7 | class DayOfMonthAnchor(Anchor): 8 | def __init__(self, day): 9 | self.__day = day 10 | 11 | def next_occurrence(self, jewish_date: JewishDate) -> Optional[JewishDate]: 12 | occurrence = JewishDate(jewish_date.jewish_year, jewish_date.jewish_month, self.__day) 13 | if occurrence <= jewish_date: 14 | self._increment_month(occurrence) 15 | return occurrence 16 | 17 | def previous_occurrence(self, jewish_date: JewishDate) -> Optional[JewishDate]: 18 | occurrence = JewishDate(jewish_date.jewish_year, jewish_date.jewish_month, self.__day) 19 | if occurrence >= jewish_date: 20 | self._decrement_month(occurrence) 21 | return occurrence 22 | 23 | def current_or_previous_occurrence(self, jewish_date: JewishDate) -> Optional[JewishDate]: 24 | occurrence = JewishDate(jewish_date.jewish_year, jewish_date.jewish_month, self.__day) 25 | if occurrence > jewish_date: 26 | self._decrement_month(occurrence) 27 | return occurrence 28 | 29 | @staticmethod 30 | def _increment_month(jewish_date: JewishDate): 31 | if jewish_date.jewish_month == jewish_date.months_in_jewish_year(): 32 | jewish_date.jewish_month = 1 33 | elif jewish_date.jewish_month == 6: 34 | jewish_date.forward(29) 35 | else: 36 | jewish_date.jewish_month += 1 37 | 38 | @staticmethod 39 | def _decrement_month(jewish_date): 40 | if jewish_date.jewish_month == 1: 41 | jewish_date.jewish_month = jewish_date.months_in_jewish_year() 42 | elif jewish_date.jewish_month == 7: 43 | back_days = 30 if jewish_date.jewish_day == 30 else 29 44 | jewish_date.back(back_days) 45 | else: 46 | jewish_date.jewish_month -= 1 47 | -------------------------------------------------------------------------------- /zmanim/limudim/anchors/day_of_year_anchor.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | from zmanim.hebrew_calendar.jewish_date import JewishDate 4 | from zmanim.limudim.anchor import Anchor 5 | 6 | 7 | class DayOfYearAnchor(Anchor): 8 | def __init__(self, month, day): 9 | self.__month = month 10 | self.__day = day 11 | 12 | def next_occurrence(self, jewish_date: JewishDate) -> Optional[JewishDate]: 13 | occurrence = JewishDate(jewish_date.jewish_year, self.__month, self.__day) 14 | if occurrence <= jewish_date: 15 | occurrence.jewish_year += 1 16 | return occurrence 17 | 18 | def previous_occurrence(self, jewish_date: JewishDate) -> Optional[JewishDate]: 19 | occurrence = JewishDate(jewish_date.jewish_year, self.__month, self.__day) 20 | if occurrence >= jewish_date: 21 | occurrence.jewish_year -= 1 22 | return occurrence 23 | 24 | def current_or_previous_occurrence(self, jewish_date: JewishDate) -> Optional[JewishDate]: 25 | occurrence = JewishDate(jewish_date.jewish_year, self.__month, self.__day) 26 | if occurrence > jewish_date: 27 | occurrence.jewish_year -= 1 28 | return occurrence 29 | -------------------------------------------------------------------------------- /zmanim/limudim/calculators/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pinnymz/python-zmanim/d33b8fe499de36a696e07662197a76ebcb5ee89e/zmanim/limudim/calculators/__init__.py -------------------------------------------------------------------------------- /zmanim/limudim/calculators/amud_yomi_bavli_dirshu.py: -------------------------------------------------------------------------------- 1 | from datetime import date 2 | from fractions import Fraction 3 | from typing import Optional, Union 4 | 5 | from zmanim.hebrew_calendar.jewish_date import JewishDate 6 | from zmanim.limudim.calculators.daf_yomi_bavli import DafYomiBavli 7 | from zmanim.limudim.cycle import Cycle 8 | 9 | 10 | class AmudYomiBavliDirshu(DafYomiBavli): 11 | Units = {u[0]: u[1] + (0 if i in [0, 2, 5, 8, 9, 10, 11, 12, 21, 27, 29, 30, 31, 32, 33, 35, 36, 39] 12 | else Fraction(1, 2)) 13 | for i, u in enumerate(DafYomiBavli.Units.items())} 14 | 15 | def initial_cycle_date(self) -> JewishDate: 16 | return self._jewish_date(date(2023, 10, 16)) 17 | 18 | @staticmethod 19 | def default_units() -> dict: 20 | return AmudYomiBavliDirshu.Units 21 | 22 | def unit_step(self) -> Union[int, Fraction]: 23 | return Fraction(1, 2) # Rational numbers preferred over float 24 | 25 | def fractional_units(self) -> Optional[tuple]: 26 | return 'a', 'b' 27 | 28 | def starting_page(self, units: dict, unit_name: str) -> int: 29 | if unit_name == 'kinnim': 30 | return 22 + self.unit_step() 31 | elif unit_name == 'tamid': 32 | return 25 + self.unit_step() 33 | elif unit_name == 'midos': 34 | return 34 35 | else: 36 | return self.default_starting_page() 37 | 38 | def cycle_end_calculation(self, start_date: JewishDate, iteration: int) -> JewishDate: 39 | return start_date + (5406 - 1) 40 | 41 | def cycle_units_calculation(self, cycle: Cycle) -> dict: 42 | return self.default_units() 43 | -------------------------------------------------------------------------------- /zmanim/limudim/calculators/daf_hashavua_bavli.py: -------------------------------------------------------------------------------- 1 | from datetime import date 2 | 3 | from zmanim.hebrew_calendar.jewish_date import JewishDate 4 | from zmanim.limudim.calculators.daf_yomi_bavli import DafYomiBavli 5 | from zmanim.limudim.cycle import Cycle 6 | 7 | 8 | class DafHashavuaBavli(DafYomiBavli): 9 | def initial_cycle_date(self) -> JewishDate: 10 | return self._jewish_date(date(2005, 3, 2)) 11 | 12 | def cycle_end_calculation(self, start_date: JewishDate, iteration: int) -> JewishDate: 13 | return start_date + ((2711 * 7) - start_date.day_of_week) # 2711 pages except first week * 7 days 14 | 15 | def interval_end_calculation(self, cycle: Cycle, start_date: JewishDate) -> JewishDate: 16 | return start_date + (7 - start_date.day_of_week) 17 | 18 | def cycle_units_calculation(self, cycle: Cycle) -> dict: 19 | return self.default_units() 20 | -------------------------------------------------------------------------------- /zmanim/limudim/calculators/daf_yomi_bavli.py: -------------------------------------------------------------------------------- 1 | from datetime import date 2 | 3 | from zmanim.hebrew_calendar.jewish_date import JewishDate 4 | from zmanim.limudim.cycle import Cycle 5 | from zmanim.limudim.limud_calculator import LimudCalculator 6 | 7 | 8 | class DafYomiBavli(LimudCalculator): 9 | Units = {'berachos': 64, 'shabbos': 157, 'eruvin': 105, 'pesachim': 121, 'shekalim': 22, 'yoma': 88, 'sukkah': 56, 'beitzah': 40, 'rosh_hashanah': 35, 10 | 'taanis': 31, 'megillah': 32, 'moed_katan': 29, 'chagigah': 27, 'yevamos': 122, 'kesubos': 112, 'nedarim': 91, 'nazir': 66, 'sotah': 49, 11 | 'gitin': 90, 'kiddushin': 82, 'bava_kamma': 119, 'bava_metzia': 119, 'bava_basra': 176, 'sanhedrin': 113, 'makkos': 24, 'shevuos': 49, 12 | 'avodah_zarah': 76, 'horiyos': 14, 'zevachim': 120, 'menachos': 110, 'chullin': 142, 'bechoros': 61, 'arachin': 34, 'temurah': 34, 13 | 'kerisos': 28, 'meilah': 22, 'kinnim': 25, 'tamid': 33, 'midos': 37, 'niddah': 73} 14 | 15 | def initial_cycle_date(self) -> JewishDate: 16 | return self._jewish_date(date(1923, 9, 11)) 17 | 18 | @staticmethod 19 | def default_starting_page(): 20 | return 2 21 | 22 | def starting_page(self, units: dict, unit_name: str) -> int: 23 | if unit_name == 'kinnim': 24 | return 23 25 | elif unit_name == 'tamid': 26 | return 26 27 | elif unit_name == 'midos': 28 | return 34 29 | else: 30 | return self.default_starting_page() 31 | 32 | @staticmethod 33 | def default_units() -> dict: 34 | return DafYomiBavli.Units 35 | 36 | def cycle_end_calculation(self, start_date: JewishDate, iteration: int) -> JewishDate: 37 | duration = 2702 if iteration < 8 else 2711 38 | return start_date + (duration - 1) 39 | 40 | def cycle_units_calculation(self, cycle: Cycle) -> dict: 41 | units = self.default_units().copy() 42 | if cycle.iteration < 8: 43 | units['shekalim'] = 13 44 | return units 45 | -------------------------------------------------------------------------------- /zmanim/limudim/calculators/daf_yomi_yerushalmi.py: -------------------------------------------------------------------------------- 1 | from datetime import date 2 | 3 | from zmanim.hebrew_calendar.jewish_date import JewishDate 4 | from zmanim.limudim.interval import Interval 5 | from zmanim.limudim.limud_calculator import LimudCalculator 6 | from zmanim.limudim.unit import Unit 7 | 8 | 9 | class DafYomiYerushalmi(LimudCalculator): 10 | Units = {'berachos': 68, 'peah': 37, 'demai': 34, 'kilayim': 44, 'shviis': 31, 'terumos': 59, 'maasros': 26, 'maaser_sheni': 33, 11 | 'chalah': 28, 'orlah': 20, 'bikurim': 13, 'shabbos': 92, 'eruvin': 65, 'pesachim': 71, 'beitzah': 22, 'rosh_hashanah': 22, 12 | 'yoma': 42, 'sukkah': 26, 'taanis': 26, 'shekalim': 33, 'megilah': 34, 'chagigah': 22, 'moed_katan': 19, 'yevamos': 85, 13 | 'kesubos': 72, 'sotah': 47, 'nedarim': 40, 'nazir': 47, 'gitin': 54, 'kiddushin': 48, 'bava_kama': 44, 'bava_metzia': 37, 14 | 'bava_basra': 34, 'sanhedrin': 44, 'makos': 9, 'shevuos': 57, 'avodah_zarah': 37, 'horayos': 19, 'niddah': 13} 15 | 16 | def initial_cycle_date(self) -> JewishDate: 17 | return self._jewish_date(date(1980, 2, 2)) 18 | 19 | @staticmethod 20 | def default_units() -> dict: 21 | return DafYomiYerushalmi.Units 22 | 23 | def cycle_end_calculation(self, start_date: JewishDate, iteration: int) -> JewishDate: 24 | def found_skips_for_year(year, a, b): 25 | return len([(m, d) for m, d in self._skip_days() if a <= JewishDate(year, m, d) <= b]) 26 | 27 | def found_skips_between(a, b): 28 | return sum([found_skips_for_year(year, a, b) for year in range(a.jewish_year, b.jewish_year + 1)]) 29 | 30 | end_date = start_date + (1554 - 1) 31 | found_days = found_skips_between(start_date, end_date) 32 | while found_days > 0: 33 | start_date, end_date = end_date + 1, end_date + found_days 34 | found_days = found_skips_between(start_date, end_date) 35 | 36 | return end_date 37 | 38 | def skip_unit(self): 39 | return Unit('no_daf_today') 40 | 41 | def is_skip_interval(self, interval: Interval) -> bool: 42 | return self._matches_skip_day(interval.start_date) 43 | 44 | def _matches_skip_day(self, date: JewishDate) -> bool: 45 | return any(date.jewish_month == m and date.jewish_day == d for m, d in self._skip_days()) 46 | 47 | def _skip_days(self) -> list: 48 | return [(5, 9), (7, 10)] 49 | -------------------------------------------------------------------------------- /zmanim/limudim/calculators/mishna_yomis.py: -------------------------------------------------------------------------------- 1 | from datetime import date 2 | 3 | from zmanim.hebrew_calendar.jewish_date import JewishDate 4 | from zmanim.limudim.limud_calculator import LimudCalculator 5 | 6 | 7 | class MishnaYomis(LimudCalculator): 8 | Units = {maseches: {i + 1: p for i, p in enumerate(perakim)} for maseches, perakim in 9 | [('berachos', [5, 8, 6, 7, 5, 8, 5, 8, 5]), ('peah', [6, 8, 8, 11, 8, 11, 8, 9]), 10 | ('demai', [4, 5, 6, 7, 11, 12, 8]), ('kilayim', [9, 11, 7, 9, 8, 9, 8, 6, 10]), 11 | ('sheviis', [8, 10, 10, 10, 9, 6, 7, 11, 9, 9]), 12 | ('terumos', [10, 6, 9, 13, 9, 6, 7, 12, 7, 12, 10]), 13 | ('maasros', [8, 8, 10, 6, 8]), ('maaser_sheni', [7, 10, 13, 12, 15]), 14 | ('chalah', [9, 8, 10, 11]), ('orlah', [9, 17, 9]), ('bikurim', [11, 11, 12, 5]), 15 | ('shabbos', 16 | [11, 7, 6, 2, 4, 10, 4, 7, 7, 6, 6, 6, 7, 4, 3, 8, 8, 3, 6, 5, 3, 6, 5, 5]), 17 | ('eruvin', [10, 6, 9, 11, 9, 10, 11, 11, 4, 15]), 18 | ('pesachim', [7, 8, 8, 9, 10, 6, 13, 8, 11, 9]), 19 | ('shekalim', [7, 5, 4, 9, 6, 6, 7, 8]), ('yoma', [8, 7, 11, 6, 7, 8, 5, 9]), 20 | ('sukkah', [11, 9, 15, 10, 8]), ('beitzah', [10, 10, 8, 7, 7]), 21 | ('rosh_hashanah', [9, 8, 9, 9]), ('taanis', [7, 10, 9, 8]), 22 | ('megillah', [11, 6, 6, 10]), 23 | ('moed_katan', [10, 5, 9]), ('chagigah', [8, 7, 8]), 24 | ('yevamos', [4, 10, 10, 13, 6, 6, 6, 6, 6, 9, 7, 6, 13, 9, 10, 7]), 25 | ('kesubos', [10, 10, 9, 12, 9, 7, 10, 8, 9, 6, 6, 4, 11]), 26 | ('nedarim', [4, 5, 11, 8, 6, 10, 9, 7, 10, 8, 12]), 27 | ('nazir', [7, 10, 7, 7, 7, 11, 4, 2, 5]), ('sotah', [9, 6, 8, 5, 5, 4, 8, 7, 15]), 28 | ('gitin', [6, 7, 8, 9, 9, 7, 9, 10, 10]), 29 | ('kiddushin', [10, 10, 13, 14]), 30 | ('bava_kamma', [4, 6, 11, 9, 7, 6, 7, 7, 12, 10]), 31 | ('bava_metzia', [8, 11, 12, 12, 11, 8, 11, 9, 13, 6]), 32 | ('bava_basra', [6, 14, 8, 9, 11, 8, 4, 8, 10, 8]), 33 | ('sanhedrin', [6, 5, 8, 5, 5, 6, 11, 7, 6, 6, 6]), ('makkos', [10, 8, 16]), 34 | ('shevuos', [7, 5, 11, 13, 5, 7, 8, 6]), 35 | ('eduyos', [14, 10, 12, 12, 7, 3, 9, 7]), ('avodah_zarah', [9, 7, 10, 12, 12]), 36 | ('avos', [18, 16, 18, 22, 23, 11]), ('horiyos', [5, 7, 8]), 37 | ('zevachim', [4, 5, 6, 6, 8, 7, 6, 12, 7, 8, 8, 6, 8, 10]), 38 | ('menachos', [4, 5, 7, 5, 9, 7, 6, 7, 9, 9, 9, 5, 11]), 39 | ('chullin', [7, 10, 7, 7, 5, 7, 6, 6, 8, 4, 2, 5]), 40 | ('bechoros', [7, 9, 4, 10, 6, 12, 7, 10, 8]), 41 | ('arachin', [4, 6, 5, 4, 6, 5, 5, 7, 8]), ('temurah', [6, 3, 5, 4, 6, 5, 6]), 42 | ('kerisos', [7, 6, 10, 3, 8, 9]), 43 | ('meilah', [4, 9, 8, 6, 5, 6]), ('tamid', [4, 5, 9, 3, 6, 4, 3]), 44 | ('midos', [9, 6, 8, 7, 4]), ('kinnim', [4, 5, 6]), 45 | ('keilim', 46 | [9, 8, 8, 4, 11, 4, 6, 11, 8, 8, 9, 8, 8, 8, 6, 8, 17, 9, 10, 7, 3, 10, 5, 17, 9, 47 | 9, 12, 10, 8, 4]), 48 | ('ohalos', [8, 7, 7, 3, 7, 7, 6, 6, 16, 7, 9, 8, 6, 7, 10, 5, 5, 10]), 49 | ('negaim', [6, 5, 8, 11, 5, 8, 5, 10, 3, 10, 12, 7, 12, 13]), 50 | ('parah', [4, 5, 11, 4, 9, 5, 12, 11, 9, 6, 9, 11]), 51 | ('taharos', [9, 8, 8, 13, 9, 10, 9, 9, 9, 8]), 52 | ('mikvaos', [8, 10, 4, 5, 6, 11, 7, 5, 7, 8]), 53 | ('niddah', [7, 7, 7, 7, 9, 14, 5, 4, 11, 8]), 54 | ('machshirin', [6, 11, 8, 10, 11, 8]), ('zavim', [6, 4, 3, 7, 12]), 55 | ('tevul_yom', [5, 8, 6, 7]), ('yadayim', [5, 4, 5, 8]), ('uktzin', [6, 10, 12])] 56 | } 57 | 58 | def initial_cycle_date(self) -> JewishDate: 59 | return self._jewish_date(date(1947, 5, 20)) 60 | 61 | @staticmethod 62 | def default_units() -> dict: 63 | return MishnaYomis.Units 64 | 65 | def cycle_end_calculation(self, start_date: JewishDate, iteration: int) -> JewishDate: 66 | return start_date + (int(4192/2) - 1) 67 | 68 | def unit_step(self): 69 | return 2 70 | 71 | -------------------------------------------------------------------------------- /zmanim/limudim/calculators/parsha.py: -------------------------------------------------------------------------------- 1 | from functools import reduce 2 | from typing import Optional 3 | 4 | from zmanim.hebrew_calendar.jewish_date import JewishDate 5 | from zmanim.limudim.anchor import Anchor 6 | from zmanim.limudim.anchors.day_of_year_anchor import DayOfYearAnchor 7 | from zmanim.limudim.cycle import Cycle 8 | from zmanim.limudim.limud_calculator import LimudCalculator 9 | 10 | 11 | class Parsha(LimudCalculator): 12 | Units = ['bereishis', 'noach', 'lech_lecha', 'vayeira', 'chayei_sarah', 'toldos', 'vayeitzei', 'vayishlach', 'vayeishev', 'mikeitz', 'vayigash', 'vayechi', 13 | 'shemos', 'vaeirah', 'bo', 'beshalach', 'yisro', 'mishpatim', 'terumah', 'tetzaveh', 'ki_sisa', 'vayakheil', 'pekudei', 14 | 'vayikra', 'tzav', 'shemini', 'tazria', 'metzora', 'acharei', 'kedoshim', 'emor', 'behar', 'bechukosai', 15 | 'bamidbar', 'naso', 'behaalosecha', 'shelach', 'korach', 'chukas', 'balak', 'pinchas', 'matos', 'masei', 16 | 'devarim', 'vaeschanan', 'eikev', 'reei', 'shoftim', 'ki_seitzei', 'ki_savo', 'nitzavim', 'vayeilech', 'haazinu', 'vezos_haberacha'] 17 | 18 | Kviah = JewishDate.CHESHVAN_KISLEV_KEVIAH 19 | IsraelModifications = { 20 | (2, Kviah.chaseirim, 5): [['matos', 'masei'], ['nitzavim', 'vayeilech']], 21 | (2, Kviah.shelaimim, 7): [], 22 | (3, Kviah.kesidran, 7): [], 23 | (5, Kviah.chaseirim, 1): [], 24 | (5, Kviah.shelaimim, 3): [['nitzavim', 'vayeilech']], 25 | (7, Kviah.chaseirim, 3): [['matos', 'masei'], ['nitzavim', 'vayeilech']], 26 | (7, Kviah.shelaimim, 5): [['matos', 'masei'], ['nitzavim', 'vayeilech']], 27 | (2, Kviah.chaseirim, 3): [['vayakheil', 'pikudei'], ['tazria', 'metzora'], ['acharei', 'kedoshim'], 28 | ['behar', 'bechukosai'], ['matos', 'masei'], ['nitzavim', 'vayeilech']], 29 | (2, Kviah.shelaimim, 5): [['vayakheil', 'pikudei'], ['tazria', 'metzora'], ['acharei', 'kedoshim'], 30 | ['behar', 'bechukosai'], ['matos', 'masei'], ['nitzavim', 'vayeilech']], 31 | (3, Kviah.kesidran, 5): [['vayakheil', 'pikudei'], ['tazria', 'metzora'], ['acharei', 'kedoshim'], 32 | ['behar', 'bechukosai'], ['matos', 'masei'], ['nitzavim', 'vayeilech']], 33 | (5, Kviah.kesidran, 7): [['vayakheil', 'pikudei'], ['tazria', 'metzora'], ['acharei', 'kedoshim'], 34 | ['matos', 'masei']], 35 | (5, Kviah.shelaimim, 1): [['tazria', 'metzora'], ['acharei', 'kedoshim'], ['behar', 'bechukosai'], 36 | ['matos', 'masei']], 37 | (7, Kviah.chaseirim, 1): [['vayakheil', 'pikudei'], ['tazria', 'metzora'], ['acharei', 'kedoshim'], 38 | ['behar', 'bechukosai'], ['matos', 'masei']], 39 | (7, Kviah.shelaimim, 3): [['vayakheil', 'pikudei'], ['tazria', 'metzora'], ['acharei', 'kedoshim'], 40 | ['behar', 'bechukosai'], ['matos', 'masei']], 41 | } 42 | 43 | DiasporaModifications = { 44 | (2, Kviah.chaseirim, 5): [['chukas', 'balak'], ['matos', 'masei'], ['nitzavim', 'vayeilech']], 45 | (2, Kviah.shelaimim, 7): [['matos', 'masei']], 46 | (3, Kviah.kesidran, 7): [['matos', 'masei']], 47 | (5, Kviah.chaseirim, 1): [], 48 | (5, Kviah.shelaimim, 3): [['nitzavim', 'vayeilech']], 49 | (7, Kviah.chaseirim, 3): [['matos', 'masei'], ['nitzavim', 'vayeilech']], 50 | (7, Kviah.shelaimim, 5): [['chukas', 'balak'], ['matos', 'masei'], ['nitzavim', 'vayeilech']], 51 | (2, Kviah.chaseirim, 3): [['vayakheil', 'pikudei'], ['tazria', 'metzora'], ['acharei', 'kedoshim'], 52 | ['behar', 'bechukosai'], ['matos', 'masei'], ['nitzavim', 'vayeilech']], 53 | (2, Kviah.shelaimim, 5): [['vayakheil', 'pikudei'], ['tazria', 'metzora'], ['acharei', 'kedoshim'], 54 | ['behar', 'bechukosai'], ['chukas', 'balak'], ['matos', 'masei'], 55 | ['nitzavim', 'vayeilech']], 56 | (3, Kviah.kesidran, 5): [['vayakheil', 'pikudei'], ['tazria', 'metzora'], ['acharei', 'kedoshim'], 57 | ['behar', 'bechukosai'], ['chukas', 'balak'], ['matos', 'masei'], 58 | ['nitzavim', 'vayeilech']], 59 | (5, Kviah.kesidran, 7): [['vayakheil', 'pikudei'], ['tazria', 'metzora'], ['acharei', 'kedoshim'], 60 | ['behar', 'bechukosai'], ['matos', 'masei']], 61 | (5, Kviah.shelaimim, 1): [['tazria', 'metzora'], ['acharei', 'kedoshim'], ['behar', 'bechukosai'], 62 | ['matos', 'masei']], 63 | (7, Kviah.chaseirim, 1): [['vayakheil', 'pikudei'], ['tazria', 'metzora'], ['acharei', 'kedoshim'], 64 | ['behar', 'bechukosai'], ['matos', 'masei']], 65 | (7, Kviah.shelaimim, 3): [['vayakheil', 'pikudei'], ['tazria', 'metzora'], ['acharei', 'kedoshim'], 66 | ['behar', 'bechukosai'], ['matos', 'masei'], ['nitzavim', 'vayeilech']], 67 | } 68 | 69 | def __init__(self, in_israel: bool = False): 70 | self.__in_israel = in_israel 71 | 72 | @property 73 | def in_israel(self) -> bool: 74 | return self.__in_israel 75 | 76 | def is_tiered_units(self) -> bool: 77 | return False 78 | 79 | def perpetual_cycle_anchor(self) -> Anchor: 80 | return DayOfYearAnchor(7, 23 if self.in_israel else 24) 81 | 82 | @staticmethod 83 | def default_units() -> list: 84 | return Parsha.Units 85 | 86 | def cycle_end_calculation(self, start_date: JewishDate, iteration: Optional[int]) -> JewishDate: 87 | return self.perpetual_cycle_anchor().next_occurrence(start_date) - 1 88 | 89 | def interval_end_calculation(self, cycle: Cycle, start_date: JewishDate) -> JewishDate: 90 | if self.in_israel: 91 | skips = [[1, range(15,22)], [3, [6]], [7, [1, 2, 10] + list(range(15,22))]] 92 | else: 93 | skips = [[1, range(15,23)], [3, [6, 7]], [7, [1, 2, 10] + list(range(15,23))]] 94 | 95 | end_date = start_date + (7 - start_date.day_of_week) 96 | 97 | while next(((month, days) for month, days in skips if month == end_date.jewish_month and end_date.jewish_day in days), None) is not None: 98 | end_date += 7 99 | 100 | return cycle.end_date if end_date > cycle.end_date else end_date 101 | 102 | def cycle_units_calculation(self, cycle: Cycle) -> list: 103 | kviah_values = cycle.start_date.kviah() 104 | if self.in_israel: 105 | modifications = Parsha.IsraelModifications[kviah_values] 106 | else: 107 | modifications = Parsha.DiasporaModifications[kviah_values] 108 | 109 | def modification_reducer(transitioned_units, parsha_pair): 110 | index = transitioned_units.index(parsha_pair[0]) 111 | return transitioned_units[0:index] + [parsha_pair] + transitioned_units[index+2:] 112 | 113 | return reduce(modification_reducer, modifications, self.default_units().copy()) 114 | -------------------------------------------------------------------------------- /zmanim/limudim/calculators/pirkei_avos.py: -------------------------------------------------------------------------------- 1 | from itertools import zip_longest 2 | from math import ceil 3 | from typing import Optional 4 | 5 | from zmanim.hebrew_calendar.jewish_date import JewishDate 6 | from zmanim.limudim.anchor import Anchor 7 | from zmanim.limudim.anchors.day_of_year_anchor import DayOfYearAnchor 8 | from zmanim.limudim.cycle import Cycle 9 | from zmanim.limudim.interval import Interval 10 | from zmanim.limudim.limud_calculator import LimudCalculator 11 | 12 | 13 | class PirkeiAvos(LimudCalculator): 14 | def __init__(self, in_israel: bool = False): 15 | self.__in_israel = in_israel 16 | 17 | @property 18 | def in_israel(self) -> bool: 19 | return self.__in_israel 20 | 21 | def is_tiered_units(self) -> bool: 22 | return False 23 | 24 | def perpetual_cycle_anchor(self) -> Anchor: 25 | return DayOfYearAnchor(1, 22 if self.in_israel else 23) # Day after Pesach 26 | 27 | @staticmethod 28 | def default_units() -> list: 29 | # 4 sub-cycles of 6 perakim, with the last sub-cycle being compressed as needed 30 | basic_units = list(range(1, 7)) 31 | return basic_units * 4 32 | 33 | def cycle_end_calculation(self, start_date: JewishDate, iteration: Optional[int]) -> JewishDate: 34 | rosh_hashana = JewishDate(start_date.jewish_year + 1, 7, 1) 35 | return rosh_hashana - rosh_hashana.day_of_week # last Shabbos before Rosh Hashanah 36 | 37 | def interval_end_calculation(self, cycle: Cycle, start_date: JewishDate) -> JewishDate: 38 | return start_date + (7 - start_date.day_of_week) 39 | 40 | def is_skip_interval(self, interval: Interval) -> bool: 41 | return (not self.in_israel) and [interval.end_date.jewish_month, interval.end_date.jewish_day] == [3, 7] 42 | 43 | def cycle_units_calculation(self, cycle: Cycle) -> list: 44 | base_units = self.default_units() 45 | cycle_weeks = int(ceil(((cycle.end_date - cycle.start_date).days + 1) / 7.0)) 46 | # If the cycle starts on a Friday, outside of israel the 2nd day of Shavuos will fall on Shabbos 47 | # and we lose one week in the pirkei avos cycle 48 | if (not self.in_israel) and cycle.start_date.day_of_week == 6: 49 | cycle_weeks -= 1 50 | unit_count = len(base_units) 51 | compress_weeks = (unit_count - cycle_weeks) * 2 52 | return base_units[:unit_count - compress_weeks] + \ 53 | list(self._each_slice(base_units[-compress_weeks:] if compress_weeks > 0 else [], 2)) 54 | 55 | @staticmethod 56 | def _each_slice(iterable, n, fillvalue=None): 57 | args = [iter(iterable)] * n 58 | return zip_longest(*args, fillvalue=fillvalue) 59 | -------------------------------------------------------------------------------- /zmanim/limudim/calculators/tehillim_monthly.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | from zmanim.hebrew_calendar.jewish_date import JewishDate 4 | from zmanim.limudim.anchor import Anchor 5 | from zmanim.limudim.anchors.day_of_month_anchor import DayOfMonthAnchor 6 | from zmanim.limudim.interval import Interval 7 | from zmanim.limudim.limud_calculator import LimudCalculator 8 | from zmanim.limudim.unit import Unit 9 | 10 | 11 | class TehillimMonthly(LimudCalculator): 12 | def is_tiered_units(self) -> bool: 13 | return False 14 | 15 | def perpetual_cycle_anchor(self) -> Anchor: 16 | return DayOfMonthAnchor(1) 17 | 18 | @staticmethod 19 | def default_units() -> list: 20 | return [9, 17, 22, 28, 34, 38, 43, 48, 54, 59, 65, 68, 71, 76, 78, 82, 87, 89, 96, 103, 105, 107, 112, 118, 119, 21 | 119, 134, 139, 144, 150] 22 | 23 | def cycle_end_calculation(self, start_date: JewishDate, iteration: Optional[int]) -> JewishDate: 24 | return self.perpetual_cycle_anchor().next_occurrence(start_date) - 1 25 | 26 | def unit_for_interval(self, units: list, interval: Interval) -> Unit: 27 | if interval.iteration == 1: 28 | start, stop = [1, units[interval.iteration - 1]] 29 | elif interval.iteration == 25: 30 | start, stop = [[119, 1], [119, 30]] 31 | elif interval.iteration == 26: 32 | start, stop = [[119, 40], [119, 400]] 33 | else: 34 | start, stop = [units[interval.iteration - 2] + 1, units[interval.iteration - 1]] 35 | 36 | if interval.end_date.jewish_day == 29 and interval.end_date.days_in_jewish_month() == 29: 37 | stop = units[interval.iteration] 38 | 39 | return Unit(start, stop) 40 | -------------------------------------------------------------------------------- /zmanim/limudim/cycle.py: -------------------------------------------------------------------------------- 1 | from typing import Callable, Optional 2 | 3 | from zmanim.hebrew_calendar.jewish_date import JewishDate 4 | from zmanim.limudim.anchor import Anchor 5 | 6 | 7 | class Cycle: 8 | def __init__(self, start_date: JewishDate, end_date: JewishDate, iteration: Optional[int]): 9 | self.__start_date = start_date 10 | self.__end_date = end_date 11 | self.__iteration = iteration 12 | 13 | def __repr__(self): 14 | return "%s(start_date=%r, end_date=%r, iteration=%r)" % \ 15 | (self.__module__ + "." + self.__class__.__qualname__, 16 | self.start_date, self.end_date, self.iteration) 17 | 18 | @property 19 | def start_date(self) -> JewishDate: 20 | return self.__start_date 21 | 22 | @property 23 | def end_date(self) -> JewishDate: 24 | return self.__end_date 25 | 26 | @property 27 | def iteration(self) -> Optional[int]: 28 | return self.__iteration 29 | 30 | @staticmethod 31 | def from_perpetual_anchor(anchor: Anchor, cycle_end_calculation: Callable[[JewishDate, Optional[int]], JewishDate], date: JewishDate) -> 'Cycle': 32 | start_date = anchor.current_or_previous_occurrence(date) 33 | end_date = cycle_end_calculation(start_date, None) 34 | return Cycle(start_date, end_date, None) 35 | 36 | @staticmethod 37 | def from_cycle_initiation(initial_cycle_date: JewishDate, cycle_end_calculation: Callable[[JewishDate, Optional[int]], JewishDate], date: JewishDate) -> Optional['Cycle']: 38 | if initial_cycle_date > date: 39 | return None 40 | iteration = 1 41 | end_date = cycle_end_calculation(initial_cycle_date, iteration) 42 | cycle = Cycle(initial_cycle_date, end_date, iteration) 43 | while date > cycle.end_date: 44 | cycle = cycle.next(cycle_end_calculation) 45 | return cycle 46 | 47 | def next(self, cycle_end_calculation: Callable[[JewishDate, Optional[int]], JewishDate]) -> Optional['Cycle']: 48 | if self.iteration is None: 49 | return None 50 | new_iteration = self.iteration + 1 51 | new_start_date = self.end_date + 1 52 | new_end_date = cycle_end_calculation(new_start_date, new_iteration) 53 | return Cycle(new_start_date, new_end_date, new_iteration) 54 | -------------------------------------------------------------------------------- /zmanim/limudim/interval.py: -------------------------------------------------------------------------------- 1 | from typing import Callable, Optional 2 | 3 | from zmanim.hebrew_calendar.jewish_date import JewishDate 4 | from zmanim.limudim.cycle import Cycle 5 | 6 | 7 | class Interval: 8 | def __init__(self, start_date: JewishDate, end_date: JewishDate, iteration: int, cycle: Cycle): 9 | self.__start_date = start_date 10 | self.__end_date = end_date 11 | self.__iteration = iteration 12 | self.__cycle = cycle 13 | 14 | def __repr__(self): 15 | return "%s(start_date=%r, end_date=%r, iteration=%r, cycle=%r)" % \ 16 | (self.__module__ + "." + self.__class__.__qualname__, 17 | self.start_date, self.end_date, self.iteration, self.cycle) 18 | 19 | @property 20 | def start_date(self) -> JewishDate: 21 | return self.__start_date 22 | 23 | @property 24 | def end_date(self) -> JewishDate: 25 | return self.__end_date 26 | 27 | @property 28 | def iteration(self) -> int: 29 | return self.__iteration 30 | 31 | @property 32 | def cycle(self) -> Cycle: 33 | return self.__cycle 34 | 35 | @staticmethod 36 | def first_for_cycle(cycle: Cycle, interval_end_calculation: Callable[[Cycle, JewishDate], JewishDate]) -> 'Interval': 37 | start_date = cycle.start_date 38 | iteration = 1 39 | end_date = interval_end_calculation(cycle, start_date) 40 | return Interval(start_date, end_date, iteration, cycle) 41 | 42 | def next(self, interval_end_calculation: Callable[[Cycle, JewishDate], JewishDate]) -> Optional['Interval']: 43 | return self._next_for_iteration(self.iteration+1, interval_end_calculation) 44 | 45 | def skip(self, interval_end_calculation: Callable[[Cycle, JewishDate], JewishDate]) -> Optional['Interval']: 46 | return self._next_for_iteration(self.iteration, interval_end_calculation) 47 | 48 | def _next_for_iteration(self, new_iteration: int, interval_end_calculation: Callable[[Cycle, JewishDate], JewishDate]) -> Optional['Interval']: 49 | if self.end_date >= self.cycle.end_date: # paranoid check to remain in cycle bounds 50 | return None 51 | new_start_date = self.end_date + 1 52 | new_end_date = interval_end_calculation(self.cycle, new_start_date) 53 | return Interval(new_start_date, new_end_date, new_iteration, self.cycle) 54 | -------------------------------------------------------------------------------- /zmanim/limudim/limud.py: -------------------------------------------------------------------------------- 1 | from typing import Optional 2 | 3 | from zmanim.hebrew_calendar.jewish_date import JewishDate 4 | from zmanim.limudim.cycle import Cycle 5 | from zmanim.limudim.interval import Interval 6 | from zmanim.limudim.unit import Unit 7 | 8 | 9 | class Limud: 10 | def __init__(self, interval: Interval, unit: Optional[Unit]): 11 | self.__interval = interval 12 | self.__unit = unit 13 | 14 | def __repr__(self): 15 | return "%s(interval=%r, unit=%r)" % \ 16 | (self.__module__ + "." + self.__class__.__qualname__, 17 | self.interval, self.unit) 18 | 19 | @property 20 | def interval(self) -> Interval: 21 | return self.__interval 22 | 23 | @property 24 | def unit(self) -> Optional[Unit]: 25 | return self.__unit 26 | 27 | def clear(self): 28 | self.__unit = None 29 | 30 | def cycle(self) -> Cycle: 31 | return self.interval.cycle 32 | 33 | def description(self) -> str: 34 | return str(self.unit) if self.unit is not None else '' 35 | 36 | def start_date(self) -> JewishDate: 37 | return self.interval.start_date 38 | 39 | def end_date(self) -> JewishDate: 40 | return self.interval.end_date 41 | 42 | def iteration(self) -> int: 43 | return self.interval.iteration 44 | 45 | def cycle_start_date(self) -> JewishDate: 46 | return self.cycle().start_date 47 | 48 | def cycle_end_date(self) -> JewishDate: 49 | return self.cycle().end_date 50 | 51 | def cycle_iteration(self) -> Optional[int]: 52 | return self.cycle().iteration 53 | -------------------------------------------------------------------------------- /zmanim/limudim/limud_calculator.py: -------------------------------------------------------------------------------- 1 | from datetime import date 2 | from fractions import Fraction 3 | from functools import reduce 4 | from numbers import Number 5 | from typing import Optional, Union 6 | 7 | from zmanim.hebrew_calendar.jewish_date import JewishDate 8 | from zmanim.limudim.anchor import Anchor 9 | from zmanim.limudim.cycle import Cycle 10 | from zmanim.limudim.interval import Interval 11 | from zmanim.limudim.limud import Limud 12 | from zmanim.limudim.unit import Unit 13 | 14 | 15 | class LimudCalculator: 16 | def limud(self, limud_date: Union[date, JewishDate]) -> Optional[Limud]: 17 | jewish_date = self._jewish_date(limud_date) 18 | cycle = self.find_cycle(jewish_date) 19 | if cycle is None or cycle.end_date < jewish_date: 20 | return None 21 | units = self.cycle_units_calculation(cycle) 22 | interval = Interval.first_for_cycle(cycle, self.interval_end_calculation) 23 | while not interval.start_date <= jewish_date <= interval.end_date: 24 | if self.is_skip_interval(interval): 25 | interval = interval.skip(self.interval_end_calculation) 26 | else: 27 | interval = interval.next(self.interval_end_calculation) 28 | 29 | unit = self.unit_for_interval(units, interval) 30 | return Limud(interval, unit) 31 | 32 | # Jewish Date on which the first cycle starts (if not perpetual) 33 | def initial_cycle_date(self) -> Optional[JewishDate]: 34 | return None 35 | 36 | # Anchor on which a cycle resets (where relevant) 37 | # e.g. for Parsha this would be a Day-of-Year anchor 38 | def perpetual_cycle_anchor(self) -> Optional[Anchor]: 39 | return None 40 | 41 | # Number of units to apply over an iteration 42 | def unit_step(self) -> Union[int, Fraction]: 43 | return 1 44 | 45 | # Are units components of some larger grouping? (e.g. pages or mishnayos) 46 | def is_tiered_units(self) -> bool: 47 | return True 48 | 49 | # For tiered units, this would be a dict in the format: 50 | # `{'some_name': last_page, ...}` 51 | # or: 52 | # `{'maseches': {perek_number: mishnayos, ...}, ...}`. 53 | # 54 | # For simple units, use a list in the format: 55 | # `['some_name', ...]` 56 | @staticmethod 57 | def default_units() -> Union[dict, list]: 58 | return [] 59 | 60 | # Set if units are applied fractionally (indicated by a fractional unit_step). 61 | # For example, an amud yomi calculator would set `('a', 'b')` 62 | def fractional_units(self) -> Optional[tuple]: 63 | return None 64 | 65 | # Change this when using page numbers that do not generally start from one. 66 | # (e.g. Talmud Bavli pages start from 2) 67 | @staticmethod 68 | def default_starting_page() -> int: 69 | return 1 70 | 71 | def starting_page(self, units: Union[dict, list], unit_name: str) -> int: 72 | return self.default_starting_page() 73 | 74 | def cycle_end_calculation(self, start_date: JewishDate, iteration: Optional[int]) -> JewishDate: 75 | return start_date 76 | 77 | def interval_end_calculation(self, cycle: Cycle, start_date: JewishDate) -> JewishDate: 78 | return start_date 79 | 80 | def cycle_units_calculation(self, cycle: Cycle) -> Union[dict, list]: 81 | return self.default_units() 82 | 83 | def unit_for_interval(self, units: Union[dict, list], interval: Interval) -> Optional[Unit]: 84 | if self.is_skip_interval(interval): 85 | return self.skip_unit() 86 | if self.is_tiered_units(): 87 | return self.tiered_units_for_interval(units, interval) 88 | if len(units) >= interval.iteration: 89 | unit = units[interval.iteration-1] 90 | return Unit(unit) if isinstance(unit, str) or not isinstance(unit, (list, tuple)) else Unit(*unit) 91 | return None 92 | 93 | def skip_unit(self) -> Optional[Unit]: 94 | return None 95 | 96 | def is_skip_interval(self, interval: Interval) -> bool: 97 | return False 98 | 99 | def base_unit(self) -> Union[int, Fraction]: 100 | return self.unit_step() if self.fractional_units() else 1 101 | 102 | def tiered_units_for_interval(self, units: Union[dict, list], interval: Interval) -> Optional[Unit]: 103 | iteration = interval.iteration 104 | offset = ((iteration - 1) * self.unit_step()) + self.base_unit() 105 | offset2 = (offset - 1) + self.unit_step() if self.unit_step() > 1 else None 106 | offsets = list(filter(None.__ne__, [offset, offset2])) 107 | targets = [[o, []] for o in offsets] 108 | results = self.find_offset_units(units, targets) 109 | if {r[0] for r in results} != {0}: 110 | return None 111 | paths = list(map(lambda r: r[1], results)) 112 | if self.fractional_units(): 113 | paths = list(map(lambda p: self._resolve_fractional_path(p), paths)) 114 | return Unit(*paths) 115 | 116 | def find_offset_units(self, units: Union[dict, list], targets: list) -> list: 117 | def unit_reducer(t: list, name: str): 118 | attributes = units[name] 119 | if isinstance(attributes, (int, Fraction)): 120 | start = self.starting_page(units, name) 121 | length = (attributes - start) + self.base_unit() 122 | 123 | head = [e for e in t if e[0] == 0] 124 | tail = [[0, p + [name, (start + o) - self.base_unit()]] if o <= length else [o - length, p] for o, p in t if o != 0] 125 | return head + tail 126 | else: 127 | head = [e for e in t if e[0] == 0] 128 | offset_units = self.find_offset_units(attributes, [[o, p + [name]] for o, p in t if o != 0]) 129 | tail = [[o, p] if o == 0 else [o, p[:-1]] for o, p in offset_units] 130 | return head + tail 131 | 132 | return list(reduce(unit_reducer, units, targets)) 133 | 134 | def find_cycle(self, date: JewishDate): 135 | if self.initial_cycle_date() is not None: 136 | return Cycle.from_cycle_initiation(self.initial_cycle_date(), self.cycle_end_calculation, date) 137 | elif self.perpetual_cycle_anchor() is not None: 138 | return Cycle.from_perpetual_anchor(self.perpetual_cycle_anchor(), self.cycle_end_calculation, date) 139 | else: 140 | raise NotImplementedError 141 | 142 | @staticmethod 143 | def _jewish_date(date): 144 | return date if isinstance(date, JewishDate) else JewishDate(date) 145 | 146 | def _resolve_fractional_path(self, path: Union[list, Number]) -> Union[list, Number]: 147 | if isinstance(path, Number): 148 | index = int((path - int(path)) * len(self.fractional_units())) 149 | return [int(path), self.fractional_units()[index]] 150 | elif isinstance(path, list): 151 | return path[:-1] + self._resolve_fractional_path(path[-1]) 152 | else: 153 | return path -------------------------------------------------------------------------------- /zmanim/limudim/unit.py: -------------------------------------------------------------------------------- 1 | from typing import Optional, Callable, Any 2 | 3 | 4 | class Unit: 5 | def __init__(self, *components): 6 | self.__components = components 7 | 8 | def __repr__(self): 9 | return "%s(components=%r)" % \ 10 | (self.__module__ + "." + self.__class__.__qualname__, 11 | self.components) 12 | 13 | @property 14 | def components(self) -> tuple: 15 | return self.__components 16 | 17 | def __str__(self): 18 | return self.render(str) 19 | 20 | def render(self, rendering_method: Callable[[Any], str]) -> str: 21 | def component_wrapper(component): 22 | if isinstance(component, str) or not isinstance(component, list): 23 | return [component] 24 | else: 25 | return component 26 | 27 | primary, *tail = map(lambda c: list(map(rendering_method, component_wrapper(c))), self.__components) 28 | secondary = tail[0] if len(tail) > 0 else None 29 | return self._render_with_root(primary) + self._render_secondary(secondary, primary) 30 | 31 | def _render_with_root(self, component: list) -> str: 32 | if len(component) == 0: 33 | return '' 34 | root, *extension = component 35 | if len(extension) == 0: 36 | return str(root) 37 | else: 38 | return str(root) + ' ' + self._render_extension(extension) 39 | 40 | @staticmethod 41 | def _render_extension(extension: list) -> str: 42 | if len(extension) == 1: 43 | return str(extension[0]) 44 | else: 45 | delimiter = '' if Unit._is_character_extension(extension[-1]) else ':' 46 | return Unit._render_extension(extension[:-1]) + delimiter + str(extension[-1]) 47 | 48 | @staticmethod 49 | def _is_character_extension(component: Any) -> bool: 50 | # single character extensions are appended directly as 'amud', R-to-L markers should be ignored 51 | return isinstance(component, str) and not component.isnumeric() and len(component.replace(u'\u200f', '')) == 1 52 | 53 | def _render_secondary(self, second_component: list, first_component: list) -> str: 54 | if second_component is None: 55 | return '' 56 | elif second_component[0] != first_component[0]: 57 | return ' - ' + self._render_with_root(second_component) 58 | diff = self._render_difference(second_component, first_component) 59 | if diff is not None: 60 | return '-' + diff 61 | else: 62 | return '' 63 | 64 | def _render_difference(self, rendering: list, comparing: list) -> Optional[str]: 65 | if len(rendering) == 0: 66 | return None 67 | elif rendering[0] != comparing[0]: 68 | return self._render_extension(rendering) 69 | else: 70 | return self._render_difference(rendering[1:], comparing[1:]) 71 | -------------------------------------------------------------------------------- /zmanim/util/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pinnymz/python-zmanim/d33b8fe499de36a696e07662197a76ebcb5ee89e/zmanim/util/__init__.py -------------------------------------------------------------------------------- /zmanim/util/astronomical_calculations.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | 4 | class AstronomicalCalculations: 5 | GEOMETRIC_ZENITH = 90.0 6 | 7 | def __init__(self): 8 | self.refraction = 34 / 60.0 9 | self.solar_radius = 16 / 60.0 10 | self.earth_radius = 6356.9 # km 11 | 12 | def elevation_adjustment(self, elevation: float) -> float: 13 | return math.degrees(math.acos(self.earth_radius / (self.earth_radius + (elevation / 1000.0)))) 14 | 15 | def adjusted_zenith(self, zenith: float, elevation: float) -> float: 16 | if zenith != self.GEOMETRIC_ZENITH: 17 | return zenith 18 | return zenith + self.solar_radius + self.refraction + self.elevation_adjustment(elevation) -------------------------------------------------------------------------------- /zmanim/util/geo_location.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | from typing import Optional 3 | 4 | from dateutil import tz 5 | 6 | from zmanim.util.math_helper import MathHelper 7 | 8 | 9 | class GeoLocation(MathHelper): 10 | 11 | def __init__(self, name: str, latitude: float, longitude: float, time_zone, elevation: Optional[float] = None): 12 | self.location_name = name 13 | self.latitude = latitude 14 | self.longitude = longitude 15 | self.time_zone = time_zone 16 | self.elevation = elevation 17 | 18 | @property 19 | def latitude(self) -> float: 20 | return self.__latitude 21 | 22 | @latitude.setter 23 | def latitude(self, latitude): 24 | if isinstance(latitude, (int, float)): 25 | if latitude > 90 or latitude < -90: 26 | raise ValueError("latitude must be in the range -90..90") 27 | self.__latitude = float(latitude) 28 | elif isinstance(latitude, (list,tuple)) and len(latitude) == 4: 29 | degrees, minutes, seconds, direction = latitude[0], latitude[1], latitude[2], latitude[3] 30 | temp = degrees + ((minutes + (seconds / 60.0)) / 60.0) 31 | if temp < 0: 32 | raise ValueError("latitude as cartography must be positive") 33 | if direction == 'S': 34 | temp *= -1 35 | elif direction != 'N': 36 | raise ValueError("direction must be either 'N' or 'S'") 37 | self.__latitude = temp 38 | else: 39 | raise TypeError("input must be a number or a list in the format 'degrees,minutes,seconds,direction'") 40 | 41 | @property 42 | def longitude(self) -> float: 43 | return self.__longitude 44 | 45 | @longitude.setter 46 | def longitude(self, longitude): 47 | if isinstance(longitude, (int, float)): 48 | if longitude > 180 or longitude < -180: 49 | raise ValueError("longitude must be in the range -180..180") 50 | self.__longitude = float(longitude) 51 | elif isinstance(longitude, (list,tuple)) and len(longitude) == 4: 52 | degrees, minutes, seconds, direction = longitude[0], longitude[1], longitude[2], longitude[3] 53 | temp = degrees + ((minutes + (seconds / 60.0)) / 60.0) 54 | if temp < 0: 55 | raise ValueError("longitude as cartography must be positive") 56 | if direction == 'W': 57 | temp *= -1 58 | elif direction != 'E': 59 | raise ValueError("direction must be either 'E' or 'W'") 60 | self.__longitude = temp 61 | else: 62 | raise TypeError("input must be a number or a list in the format 'degrees,minutes,seconds,direction'") 63 | 64 | @property 65 | def time_zone(self) -> tz.tzfile: 66 | return self.__time_zone 67 | 68 | @time_zone.setter 69 | def time_zone(self, time_zone): 70 | if isinstance(time_zone, str): 71 | self.__time_zone = tz.gettz(time_zone) 72 | elif isinstance(time_zone, tz.tzfile): 73 | self.__time_zone = time_zone 74 | else: 75 | raise TypeError("input must be a timezone or string") 76 | 77 | @property 78 | def elevation(self) -> float: 79 | return self.__elevation 80 | 81 | @elevation.setter 82 | def elevation(self, elevation): 83 | if elevation is None: 84 | elevation = 0 85 | if elevation < 0: 86 | raise ValueError("elevation cannot be negative") 87 | self.__elevation = float(elevation) 88 | 89 | def __repr__(self): 90 | return "%s(name=%r, latitude=%r, longitude=%r, time_zone=%r, elevation=%r)" % \ 91 | (self.__module__ + "." + self.__class__.__qualname__, self.location_name, self.latitude, self.longitude, 92 | self.time_zone, self.elevation) 93 | 94 | @classmethod 95 | def GMT(cls): 96 | return cls('Greenwich, England', 51.4772, 0, 'GMT') 97 | 98 | def antimeridian_adjustment(self) -> int: 99 | local_hours_offset = self.local_mean_time_offset() / float(self.HOUR_MILLIS) 100 | if local_hours_offset >= 20: 101 | return 1 102 | elif local_hours_offset <= -20: 103 | return -1 104 | else: 105 | return 0 106 | 107 | def local_mean_time_offset(self) -> float: 108 | return (self.longitude * 4 * self.MINUTE_MILLIS) - self.standard_time_offset() 109 | 110 | def standard_time_offset(self) -> int: 111 | now = datetime.now(tz=self.time_zone) 112 | return int((now.utcoffset() - now.dst()).total_seconds()) * 1000 113 | 114 | def time_zone_offset_at(self, utc_time: datetime) -> float: 115 | return utc_time.astimezone(self.time_zone).utcoffset().total_seconds() / 3600.0 116 | -------------------------------------------------------------------------------- /zmanim/util/math_helper.py: -------------------------------------------------------------------------------- 1 | class MathHelper: 2 | MINUTE_MILLIS = 60 * 1000 3 | HOUR_MILLIS = MINUTE_MILLIS * 60 -------------------------------------------------------------------------------- /zmanim/util/noaa_calculator.py: -------------------------------------------------------------------------------- 1 | import math 2 | from datetime import date, datetime, time 3 | from typing import Optional 4 | 5 | import julian 6 | 7 | from zmanim.util.astronomical_calculations import AstronomicalCalculations 8 | from zmanim.util.geo_location import GeoLocation 9 | 10 | 11 | class NOAACalculator(AstronomicalCalculations): 12 | JULIAN_DAY_JAN_1_2000 = 2451545.0 13 | JULIAN_DAYS_PER_CENTURY = 36525.0 14 | 15 | @staticmethod 16 | def name(): 17 | return 'US National Oceanic and Atmospheric Administration Algorithm' 18 | 19 | def utc_sunrise(self, target_date: date, geo_location: GeoLocation, zenith: float, adjust_for_elevation: bool = False) -> Optional[float]: 20 | try: 21 | return self._utc_sun_position(target_date, geo_location, zenith, adjust_for_elevation, 'sunrise') 22 | except ValueError: 23 | return None 24 | 25 | def utc_sunset(self, target_date: date, geo_location: GeoLocation, zenith: float, adjust_for_elevation: bool = False) -> Optional[float]: 26 | try: 27 | return self._utc_sun_position(target_date, geo_location, zenith, adjust_for_elevation, 'sunset') 28 | except ValueError: 29 | return None 30 | 31 | def _julian_centuries_from_julian_day(self, julian_day: float) -> float: 32 | return (julian_day - self.JULIAN_DAY_JAN_1_2000) / self.JULIAN_DAYS_PER_CENTURY 33 | 34 | def _julian_day_from_julian_centuries(self, julian_centuries: float) -> float: 35 | return (julian_centuries * self.JULIAN_DAYS_PER_CENTURY) + self.JULIAN_DAY_JAN_1_2000 36 | 37 | def _utc_sun_position(self, target_date: date, geo_location: GeoLocation, zenith: float, adjust_for_elevation: bool, mode: str) -> float: 38 | if not isinstance(target_date, datetime): 39 | target_date = datetime.combine(target_date, time()) 40 | elevation = geo_location.elevation if adjust_for_elevation else 0.0 41 | adjusted_zenith = self.adjusted_zenith(zenith, elevation) 42 | utc_time = self._calculate_utc_sun_position(julian.to_jd(target_date), 43 | geo_location.latitude, 44 | -geo_location.longitude, 45 | adjusted_zenith, 46 | mode) # in minutes 47 | utc_time /= 60.0 # in hours 48 | return utc_time % 24 # normalized (0...24) 49 | 50 | def _calculate_utc_sun_position(self, julian_day: float, latitude: float, longitude: float, zenith: float, mode: str) -> float: 51 | julian_centuries = self._julian_centuries_from_julian_day(julian_day) 52 | 53 | # first pass using solar noon 54 | noonmin = self._solar_noon_utc(julian_centuries, longitude) 55 | tnoon = self._julian_centuries_from_julian_day(julian_day + (noonmin / 1440.0)) 56 | first_pass = self._approximate_utc_sun_position(tnoon, latitude, longitude, zenith, mode) 57 | 58 | # refine using output of first pass 59 | trefinement = self._julian_centuries_from_julian_day(julian_day + (first_pass / 1440.0)) 60 | return self._approximate_utc_sun_position(trefinement, latitude, longitude, zenith, mode) 61 | 62 | def _approximate_utc_sun_position(self, approx_julian_centuries: float, latitude: float, longitude: float, zenith: float, mode: str) -> float: 63 | eq_time = self._equation_of_time(approx_julian_centuries) 64 | solar_dec = self._solar_declination(approx_julian_centuries) 65 | hour_angle = self._sun_hour_angle_at_horizon(latitude, solar_dec, zenith, mode) 66 | 67 | delta = longitude - math.degrees(hour_angle) 68 | time_delta = delta * 4.0 69 | return 720 + time_delta - eq_time 70 | 71 | def _sun_hour_angle_at_horizon(self, latitude: float, solar_dec: float, zenith: float, mode: str) -> float: 72 | lat_r = math.radians(latitude) 73 | solar_dec_r = math.radians(solar_dec) 74 | zenith_r = math.radians(zenith) 75 | 76 | hour_angle = math.acos( 77 | (math.cos(zenith_r) / (math.cos(lat_r) * math.cos(solar_dec_r))) - 78 | (math.tan(lat_r) * math.tan(solar_dec_r)) 79 | ) 80 | 81 | if mode == 'sunset': 82 | hour_angle *= -1 83 | 84 | return hour_angle # in radians 85 | 86 | def _solar_declination(self, julian_centuries: float) -> float: 87 | correction = math.radians(self._obliquity_correction(julian_centuries)) 88 | apparent_longitude = math.radians(self._sun_apparent_longitude(julian_centuries)) 89 | sint = math.sin(correction) * math.sin(apparent_longitude) 90 | return math.degrees(math.asin(sint)) # in degrees 91 | 92 | def _sun_apparent_longitude(self, julian_centuries: float) -> float: 93 | true_longitude = self._sun_true_longitude(julian_centuries) 94 | omega = 125.04 - (1934.136 * julian_centuries) 95 | return true_longitude - 0.00569 - (0.00478 * math.sin(math.radians(omega))) # in degrees 96 | 97 | def _sun_true_longitude(self, julian_centuries: float) -> float: 98 | sgml = self._sun_geometric_mean_longitude(julian_centuries) 99 | center = self._sun_equation_of_center(julian_centuries) 100 | return sgml + center # in degrees 101 | 102 | def _sun_equation_of_center(self, julian_centuries: float) -> float: 103 | mrad = math.radians(self._sun_geometric_mean_anomaly(julian_centuries)) 104 | sinm = math.sin(mrad) 105 | sin2m = math.sin(2 * mrad) 106 | sin3m = math.sin(3 * mrad) 107 | 108 | return (sinm * (1.914602 - (julian_centuries * (0.004817 + (0.000014 * julian_centuries))))) + \ 109 | (sin2m * (0.019993 - (0.000101 * julian_centuries))) + \ 110 | (sin3m * 0.000289) # in degrees 111 | 112 | def _solar_noon_utc(self, julian_centuries: float, longitude: float) -> float: 113 | century_start = self._julian_day_from_julian_centuries(julian_centuries) 114 | 115 | # first pass to yield approximate solar noon 116 | approx_tnoon = self._julian_centuries_from_julian_day(century_start + (longitude / 360.0)) 117 | approx_eq_time = self._equation_of_time(approx_tnoon) 118 | approx_sol_noon = 720 + (longitude * 4) - approx_eq_time 119 | 120 | # refinement using output of first pass 121 | tnoon = self._julian_centuries_from_julian_day(century_start - 0.5 + (approx_sol_noon / 1440.0)) 122 | eq_time = self._equation_of_time(tnoon) 123 | return 720 + (longitude * 4) - eq_time 124 | 125 | def _equation_of_time(self, julian_centuries: float) -> float: 126 | epsilon = math.radians(self._obliquity_correction(julian_centuries)) 127 | sgml = math.radians(self._sun_geometric_mean_longitude(julian_centuries)) 128 | sgma = math.radians(self._sun_geometric_mean_anomaly(julian_centuries)) 129 | eoe = self._earth_orbit_eccentricity(julian_centuries) 130 | 131 | y = math.tan(epsilon / 2.0) 132 | y *= y 133 | 134 | sin2l0 = math.sin(2.0 * sgml) 135 | sin4l0 = math.sin(4.0 * sgml) 136 | cos2l0 = math.cos(2.0 * sgml) 137 | sinm = math.sin(sgma) 138 | sin2m = math.sin(2.0 * sgma) 139 | 140 | eq_time = (y * sin2l0) - (2.0 * eoe * sinm) + (4.0 * eoe * y * sinm * cos2l0) - (0.5 * y * y * sin4l0) - \ 141 | (1.25 * eoe * eoe * sin2m) 142 | return math.degrees(eq_time) * 4.0 # minutes of time 143 | 144 | def _earth_orbit_eccentricity(self, julian_centuries: float) -> float: 145 | return 0.016708634 - (julian_centuries * (0.000042037 + (0.0000001267 * julian_centuries))) # unitless 146 | 147 | def _sun_geometric_mean_anomaly(self, julian_centuries: float) -> float: 148 | anomaly = 357.52911 + (julian_centuries * (35999.05029 - (0.0001537 * julian_centuries))) # in degrees 149 | 150 | return anomaly % 360 # normalized (0...360) 151 | 152 | def _sun_geometric_mean_longitude(self, julian_centuries: float) -> float: 153 | longitude = 280.46646 + (julian_centuries * (36000.76983 + (0.0003032 * julian_centuries))) # in degrees 154 | 155 | return longitude % 360 # normalized (0...360) 156 | 157 | def _obliquity_correction(self, julian_centuries: float) -> float: 158 | obliquity_of_ecliptic = self._mean_obliquity_of_ecliptic(julian_centuries) 159 | 160 | omega = 125.04 - (1934.136 * julian_centuries) 161 | correction = obliquity_of_ecliptic + (0.00256 * math.cos(math.radians(omega))) 162 | return correction % 360 # normalized (0...360) 163 | 164 | def _mean_obliquity_of_ecliptic(self, julian_centuries: float) -> float: 165 | seconds = 21.448 - ( 166 | julian_centuries * (46.8150 + (julian_centuries * (0.00059 - (julian_centuries * 0.001813))))) 167 | return 23.0 + ((26.0 + (seconds / 60)) / 60.0) # in degrees 168 | -------------------------------------------------------------------------------- /zmanim/util/sun_times_calculator.py: -------------------------------------------------------------------------------- 1 | import math 2 | from datetime import date 3 | from typing import Optional 4 | 5 | from zmanim.util.astronomical_calculations import AstronomicalCalculations 6 | from zmanim.util.geo_location import GeoLocation 7 | 8 | 9 | class SunTimesCalculator(AstronomicalCalculations): 10 | DEG_PER_HOUR = 360.0 / 24.0 11 | 12 | @staticmethod 13 | def name(): 14 | return 'US Naval Almanac Algorithm' 15 | 16 | def utc_sunrise(self, target_date: date, geo_location: GeoLocation, zenith: float, adjust_for_elevation: bool = False) -> Optional[float]: 17 | try: 18 | return self._utc_sun_position(target_date, geo_location, zenith, adjust_for_elevation, 'sunrise') 19 | except ValueError: 20 | return None 21 | 22 | def utc_sunset(self, target_date: date, geo_location: GeoLocation, zenith: float, adjust_for_elevation: bool = False) -> Optional[float]: 23 | try: 24 | return self._utc_sun_position(target_date, geo_location, zenith, adjust_for_elevation, 'sunset') 25 | except ValueError: 26 | return None 27 | 28 | def _sin_deg(self, deg: float) -> float: 29 | return math.sin(math.radians(deg)) 30 | 31 | def _cos_deg(self, deg: float) -> float: 32 | return math.cos(math.radians(deg)) 33 | 34 | def _tan_deg(self, deg: float) -> float: 35 | return math.tan(math.radians(deg)) 36 | 37 | def _acos_deg(self, x: float) -> float: 38 | return math.degrees(math.acos(x)) 39 | 40 | def _asin_deg(self, x: float) -> float: 41 | return math.degrees(math.asin(x)) 42 | 43 | def _atan_deg(self, x: float) -> float: 44 | return math.degrees(math.atan(x)) 45 | 46 | def _utc_sun_position(self, target_date: date, geo_location: GeoLocation, zenith: float, adjust_for_elevation: bool, mode: str) -> float: 47 | elevation = geo_location.elevation if adjust_for_elevation else 0 48 | adjusted_zenith = self.adjusted_zenith(zenith, elevation) 49 | utc_time = self._calculate_utc_sun_position(target_date, 50 | geo_location.latitude, 51 | geo_location.longitude, 52 | adjusted_zenith, 53 | mode) # in hours 54 | return utc_time % 24 # normalized (0...24) 55 | 56 | def _calculate_utc_sun_position(self, target_date: date, latitude: float, longitude: float, zenith: float, mode: str) -> float: 57 | day_of_year = target_date.timetuple().tm_yday 58 | hours_offset = self._hours_from_meridian(longitude) 59 | time_days = self._approx_time_days(day_of_year, hours_offset, mode) 60 | 61 | mean_anomaly = self._sun_mean_anomaly(time_days) 62 | true_long = self._sun_true_longitude(mean_anomaly) 63 | right_ascension_hours = self._sun_right_ascension_hours(true_long) 64 | cos_local_hour_angle = self._cos_local_hour_angle(true_long, latitude, zenith) 65 | 66 | local_hour_angle = self._acos_deg(cos_local_hour_angle) 67 | if mode == 'sunrise': 68 | local_hour_angle = 360.0 - local_hour_angle 69 | 70 | local_hour = local_hour_angle / self.DEG_PER_HOUR 71 | 72 | mean_time = self._local_mean_time(local_hour, right_ascension_hours, time_days) 73 | return mean_time - hours_offset 74 | 75 | def _local_mean_time(self, local_hour: float, right_ascension_hours: float, time_days: float) -> float: 76 | return local_hour + right_ascension_hours - (0.06571 * time_days) - 6.622 77 | 78 | def _cos_local_hour_angle(self, sun_true_long: float, latitude: float, zenith: float) -> float: 79 | sin_dec = 0.39782 * self._sin_deg(sun_true_long) 80 | cos_dec = self._cos_deg(self._asin_deg(sin_dec)) 81 | return (self._cos_deg(zenith) - (sin_dec * self._sin_deg(latitude))) / (cos_dec * self._cos_deg(latitude)) 82 | 83 | def _sun_right_ascension_hours(self, sun_true_long: float) -> float: 84 | ra = self._atan_deg(0.91764 * self._tan_deg(sun_true_long)) 85 | l_quadrant = math.floor(sun_true_long / 90.0) * 90.0 86 | ra_quadrant = math.floor(ra / 90.0) * 90.0 87 | ra += (l_quadrant - ra_quadrant) 88 | 89 | return ra / self.DEG_PER_HOUR # in hours 90 | 91 | def _sun_true_longitude(self, sun_mean_anomaly: float) -> float: 92 | true_longitude = sun_mean_anomaly + \ 93 | (1.916 * self._sin_deg(sun_mean_anomaly)) + \ 94 | (0.02 * self._sin_deg(2 * sun_mean_anomaly)) + \ 95 | 282.634 96 | return true_longitude % 360 97 | 98 | def _sun_mean_anomaly(self, time_days: float) -> float: 99 | return (0.9856 * time_days) - 3.289 100 | 101 | def _approx_time_days(self, day_of_year: int, hours_offset: float, mode: str) -> float: 102 | mode_offset = 6.0 if mode == 'sunrise' else 18.0 103 | return day_of_year + ((mode_offset - hours_offset) / 24) 104 | 105 | def _hours_from_meridian(self, longitude: float) -> float: 106 | return longitude / self.DEG_PER_HOUR 107 | -------------------------------------------------------------------------------- /zmanim/zmanim_calendar.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime, timedelta 2 | from typing import Optional 3 | 4 | from zmanim.astronomical_calendar import AstronomicalCalendar 5 | from zmanim.hebrew_calendar.jewish_calendar import JewishCalendar 6 | 7 | 8 | class ZmanimCalendar(AstronomicalCalendar): 9 | def __init__(self, candle_lighting_offset: int = None, *args, **kwargs): 10 | super(ZmanimCalendar, self).__init__(*args, **kwargs) 11 | self.candle_lighting_offset = 18 if candle_lighting_offset is None else candle_lighting_offset 12 | self.use_elevation = False 13 | 14 | def __repr__(self): 15 | return "%s(candle_lighting_offset=%r, geo_location=%r, date=%r, calculator=%r)" % \ 16 | (self.__module__ + "." + self.__class__.__qualname__, self.candle_lighting_offset, 17 | self.geo_location, self.date, self.astronomical_calculator) 18 | 19 | def elevation_adjusted_sunrise(self) -> Optional[datetime]: 20 | return self.sunrise() if self.use_elevation else self.sea_level_sunrise() 21 | 22 | def hanetz(self) -> Optional[datetime]: 23 | return self.elevation_adjusted_sunrise() 24 | 25 | def elevation_adjusted_sunset(self) -> Optional[datetime]: 26 | return self.sunset() if self.use_elevation else self.sea_level_sunset() 27 | 28 | def shkia(self) -> Optional[datetime]: 29 | return self.elevation_adjusted_sunset() 30 | 31 | def tzais(self, opts: dict = {'degrees': 8.5}) -> Optional[datetime]: 32 | degrees, offset, zmanis_offset = self._extract_degrees_offset(opts) 33 | sunset_for_degrees = self.elevation_adjusted_sunset() if degrees == 0 else self.sunset_offset_by_degrees(self.GEOMETRIC_ZENITH + degrees) 34 | if zmanis_offset != 0: 35 | return self._offset_by_minutes_zmanis(sunset_for_degrees, zmanis_offset) 36 | else: 37 | return self._offset_by_minutes(sunset_for_degrees, offset) 38 | 39 | def tzais_72(self) -> Optional[datetime]: 40 | return self.tzais({'offset': 72}) 41 | 42 | def alos(self, opts: dict = {'degrees': 16.1}) -> Optional[datetime]: 43 | degrees, offset, zmanis_offset = self._extract_degrees_offset(opts) 44 | sunrise_for_degrees = self.elevation_adjusted_sunrise() if degrees == 0 else self.sunrise_offset_by_degrees(self.GEOMETRIC_ZENITH + degrees) 45 | if zmanis_offset != 0: 46 | return self._offset_by_minutes_zmanis(sunrise_for_degrees, -zmanis_offset) 47 | else: 48 | return self._offset_by_minutes(sunrise_for_degrees, -offset) 49 | 50 | def alos_72(self) -> Optional[datetime]: 51 | return self.alos({'offset': 72}) 52 | 53 | def chatzos(self) -> Optional[datetime]: 54 | return self.sun_transit() 55 | 56 | def candle_lighting(self) -> Optional[datetime]: 57 | return self._offset_by_minutes(self.sea_level_sunset(), -self.candle_lighting_offset) 58 | 59 | def sof_zman_shma(self, day_start: datetime, day_end: datetime) -> datetime: 60 | return self._shaos_into_day(day_start, day_end, 3) 61 | 62 | def sof_zman_shma_gra(self) -> datetime: 63 | return self.sof_zman_shma(self.elevation_adjusted_sunrise(), self.elevation_adjusted_sunset()) 64 | 65 | def sof_zman_shma_mga(self) -> datetime: 66 | return self.sof_zman_shma(self.alos_72(), self.tzais_72()) 67 | 68 | def sof_zman_tfila(self, day_start: Optional[datetime], day_end: Optional[datetime]) -> Optional[datetime]: 69 | return self._shaos_into_day(day_start, day_end, 4) 70 | 71 | def sof_zman_tfila_gra(self) -> Optional[datetime]: 72 | return self.sof_zman_tfila(self.elevation_adjusted_sunrise(), self.elevation_adjusted_sunset()) 73 | 74 | def sof_zman_tfila_mga(self) -> Optional[datetime]: 75 | return self.sof_zman_tfila(self.alos_72(), self.tzais_72()) 76 | 77 | def mincha_gedola(self, day_start: Optional[datetime] = None, day_end: Optional[datetime] = None) -> Optional[datetime]: 78 | if day_start is None: 79 | day_start = self.elevation_adjusted_sunrise() 80 | if day_end is None: 81 | day_end = self.elevation_adjusted_sunset() 82 | 83 | return self._shaos_into_day(day_start, day_end, 6.5) 84 | 85 | def mincha_ketana(self, day_start: Optional[datetime] = None, day_end: Optional[datetime] = None) -> Optional[datetime]: 86 | if day_start is None: 87 | day_start = self.elevation_adjusted_sunrise() 88 | if day_end is None: 89 | day_end = self.elevation_adjusted_sunset() 90 | 91 | return self._shaos_into_day(day_start, day_end, 9.5) 92 | 93 | def plag_hamincha(self, day_start: Optional[datetime] = None, day_end: Optional[datetime] = None) -> Optional[datetime]: 94 | if day_start is None: 95 | day_start = self.elevation_adjusted_sunrise() 96 | if day_end is None: 97 | day_end = self.elevation_adjusted_sunset() 98 | 99 | return self._shaos_into_day(day_start, day_end, 10.75) 100 | 101 | def shaah_zmanis(self, day_start: Optional[datetime], day_end: Optional[datetime]) -> Optional[float]: 102 | return self.temporal_hour(day_start, day_end) 103 | 104 | def shaah_zmanis_gra(self) -> Optional[float]: 105 | return self.shaah_zmanis(self.elevation_adjusted_sunrise(), self.elevation_adjusted_sunset()) 106 | 107 | def shaah_zmanis_mga(self) -> Optional[float]: 108 | return self.shaah_zmanis(self.alos_72(), self.tzais_72()) 109 | 110 | def shaah_zmanis_by_degrees_and_offset(self, degrees: float, offset: float) -> Optional[float]: 111 | opts = {'degrees': degrees, 'offset': offset} 112 | return self.shaah_zmanis(self.alos(opts), self.tzais(opts)) 113 | 114 | def is_assur_bemelacha(self, current_time: datetime, tzais=None, in_israel: Optional[bool]=False): 115 | if tzais is None: 116 | tzais_time = self.tzais() 117 | elif isinstance(tzais, dict): 118 | tzais_time = self.tzais(tzais) 119 | else: 120 | tzais_time = tzais 121 | jewish_calendar = JewishCalendar(current_time.date()) 122 | jewish_calendar.in_israel = in_israel 123 | return (current_time <= tzais_time and jewish_calendar.is_assur_bemelacha()) or \ 124 | (current_time >= self.elevation_adjusted_sunset() and jewish_calendar.is_tomorrow_assur_bemelacha()) 125 | 126 | def _shaos_into_day(self, day_start: Optional[datetime], day_end: Optional[datetime], shaos: float) -> Optional[datetime]: 127 | shaah_zmanis = self.temporal_hour(day_start, day_end) 128 | if shaah_zmanis is None: 129 | return None 130 | return self._offset_by_minutes(day_start, (shaah_zmanis / self.MINUTE_MILLIS) * shaos) 131 | 132 | def _extract_degrees_offset(self, opts: dict) -> tuple: 133 | degrees = opts['degrees'] if 'degrees' in opts else 0 134 | offset = opts['offset'] if 'offset' in opts else 0 135 | zmanis_offset = opts['zmanis_offset'] if 'zmanis_offset' in opts else 0 136 | return degrees, offset, zmanis_offset 137 | 138 | def _offset_by_minutes(self, time: Optional[datetime], minutes: float) -> Optional[datetime]: 139 | if time is None: 140 | return None 141 | return time + timedelta(minutes=minutes) 142 | 143 | def _offset_by_minutes_zmanis(self, time: Optional[datetime], minutes: float) -> Optional[datetime]: 144 | if time is None: 145 | return None 146 | shaah_zmanis_skew = self.shaah_zmanis_gra() / self.HOUR_MILLIS 147 | return time + timedelta(minutes=minutes*shaah_zmanis_skew) 148 | --------------------------------------------------------------------------------