[Git][debian-gis-team/cftime][master] 5 commits: New upstream version 1.4.0rel2+ds

Bas Couwenberg gitlab at salsa.debian.org
Mon Feb 1 05:00:35 GMT 2021



Bas Couwenberg pushed to branch master at Debian GIS Project / cftime


Commits:
66719f89 by Bas Couwenberg at 2021-02-01T05:46:19+01:00
New upstream version 1.4.0rel2+ds
- - - - -
4bc43da5 by Bas Couwenberg at 2021-02-01T05:46:20+01:00
Update upstream source from tag 'upstream/1.4.0rel2+ds'

Update to upstream version '1.4.0rel2+ds'
with Debian dir db0f9be155df15f830ca01943c243b8d31d66c30
- - - - -
a5f89314 by Bas Couwenberg at 2021-02-01T05:46:33+01:00
New upstream release.

- - - - -
8a74c8b4 by Bas Couwenberg at 2021-02-01T05:48:48+01:00
Update copyright file for license change to MIT.

- - - - -
3a1a9109 by Bas Couwenberg at 2021-02-01T05:49:03+01:00
Set distribution to unstable.

- - - - -


14 changed files:

- .coveragerc
- .github/workflows/miniconda.yml
- − COPYING
- Changelog
- + LICENSE
- MANIFEST.in
- README.md
- debian/changelog
- debian/copyright
- setup.py
- src/cftime/__init__.py
- src/cftime/_cftime.pyx
- + src/cftime/_cftime_legacy.pyx
- test/test_cftime.py


Changes:

=====================================
.coveragerc
=====================================
@@ -7,7 +7,7 @@ relative_files = True
 branch = True
 plugins = Cython.Coverage
 include =
-    cftime/*
+    src/cftime/*
 omit = 
     setup.py
     docs/*


=====================================
.github/workflows/miniconda.yml
=====================================
@@ -40,23 +40,28 @@ jobs:
       run: |
         conda create --name TEST python=${{ matrix.python-version }} --file requirements.txt --file requirements-dev.txt
         source activate TEST
-        CYTHON_COVERAGE=1 pip install -v -e  . --no-deps --force-reinstall
+        # enabling coverage slows down the tests dramaticaly
+        #CYTHON_COVERAGE=1 pip install -v -e  . --no-deps --force-reinstall
+        pip install -v -e  . --no-deps --force-reinstall
         conda info --all
         conda list
 
     - name: Run Tests
+      env:
+        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
       shell: bash -l {0}
       run: |
         source activate TEST
         py.test -vv test
 
-    - name: Coveralls
-      env:
-        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
-      if: startsWith(matrix.os,'ubuntu')
-      run: |
-        source activate TEST
-        coveralls
+#   - name: Coveralls
+#     env:
+#       GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+#       COVERALLS_REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+#     if: ${{ matrix.os =='ubuntu-latest' && matrix.python-version == '3.9' && matrix.platform == 'x64' }}
+#     run: |
+#       source activate TEST
+#       coveralls --service=github-actions
 
     - name: Tarball
       if: startsWith(matrix.os,'ubuntu')


=====================================
COPYING deleted
=====================================
@@ -1,232 +0,0 @@
-copyright: 2008 by Jeffrey Whitaker.
-
-Permission to use, copy, modify, and distribute this software and
-its documentation for any purpose and without fee is hereby granted,
-provided that the above copyright notice appear in all copies and that
-both the copyright notice and this permission notice appear in
-supporting documentation.
-
-THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
-INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
-EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR
-CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
-USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
-OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-PERFORMANCE OF THIS SOFTWARE.
-
-
-parts of pyiso8601 are included in cftime under the following license:
-
-Copyright (c) 2007 Michael Twomey
-
-Permission is hereby granted, free of charge, to any person obtaining a
-copy of this software and associated documentation files (the
-"Software"), to deal in the Software without restriction, including
-without limitation the rights to use, copy, modify, merge, publish,
-distribute, sublicense, and/or sell copies of the Software, and to
-permit persons to whom the Software is furnished to do so, subject to
-the following conditions:
-
-The above copyright notice and this permission notice shall be included
-in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
-CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
-TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
-SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-calendar calculation routines in _cftime.pyx derived from calcalcs.c by David W. Pierce with the
-following license:
-
-GNU GENERAL PUBLIC LICENSE
-
-Version 3, 29 June 2007
-
-Copyright © 2007 Free Software Foundation, Inc. <http://fsf.org/>
-
-Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
-Preamble
-
-The GNU General Public License is a free, copyleft license for software and other kinds of works.
-
-The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
-
-When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
-
-To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
-
-For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
-
-Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
-
-For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
-
-Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
-
-Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
-
-The precise terms and conditions for copying, distribution and modification follow.
-TERMS AND CONDITIONS
-0. Definitions.
-
-.This License. refers to version 3 of the GNU General Public License.
-
-.Copyright. also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
-
-.The Program. refers to any copyrightable work licensed under this License. Each licensee is addressed as .you.. .Licensees. and .recipients. may be individuals or organizations.
-
-To .modify. a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a .modified version. of the earlier work or a work .based on. the earlier work.
-
-A .covered work. means either the unmodified Program or a work based on the Program.
-
-To .propagate. a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
-
-To .convey. a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
-
-An interactive user interface displays .Appropriate Legal Notices. to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
-1. Source Code.
-
-The .source code. for a work means the preferred form of the work for making modifications to it. .Object code. means any non-source form of a work.
-
-A .Standard Interface. means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
-
-The .System Libraries. of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A .Major Component., in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
-
-The .Corresponding Source. for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
-
-The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
-
-The Corresponding Source for a work in source code form is that same work.
-2. Basic Permissions.
-
-All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
-
-You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
-
-Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
-3. Protecting Users' Legal Rights From Anti-Circumvention Law.
-
-No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
-
-When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
-4. Conveying Verbatim Copies.
-
-You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
-
-You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
-5. Conveying Modified Source Versions.
-
-You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
-
-    * a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
-    * b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to .keep intact all notices..
-    * c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
-    * d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
-
-A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an .aggregate. if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
-6. Conveying Non-Source Forms.
-
-You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
-
-    * a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
-    * b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
-    * c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
-    * d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
-    * e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
-
-A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
-
-A .User Product. is either (1) a .consumer product., which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, .normally used. refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
-
-.Installation Information. for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
-
-If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
-
-The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
-
-Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
-7. Additional Terms.
-
-.Additional permissions. are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
-
-When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
-
-Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
-
-    * a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
-    * b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
-    * c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
-    * d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
-    * e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
-    * f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
-
-All other non-permissive additional terms are considered .further restrictions. within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
-
-If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
-
-Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
-8. Termination.
-
-You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
-
-However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
-
-Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
-
-Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
-9. Acceptance Not Required for Having Copies.
-
-You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
-10. Automatic Licensing of Downstream Recipients.
-
-Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
-
-An .entity transaction. is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
-
-You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
-11. Patents.
-
-A .contributor. is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's .contributor version..
-
-A contributor's .essential patent claims. are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, .control. includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
-
-Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
-
-In the following three paragraphs, a .patent license. is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To .grant. such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
-
-If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. .Knowingly relying. means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
-
-If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
-
-A patent license is .discriminatory. if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
-
-Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
-12. No Surrender of Others' Freedom.
-
-If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
-13. Use with the GNU Affero General Public License.
-
-Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
-14. Revised Versions of this License.
-
-The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
-
-Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License .or any later version. applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
-
-If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
-
-Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
-15. Disclaimer of Warranty.
-
-THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM .AS IS. WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-16. Limitation of Liability.
-
-IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
-17. Interpretation of Sections 15 and 16.
-
-If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
-
-END OF TERMS AND CONDITIONS


=====================================
Changelog
=====================================
@@ -1,3 +1,16 @@
+version 1.4.0 (release tag v1.4.0.rel)
+======================================
+ * `cftime.date2num` will now always return an array of integers, if the units
+   and times allow.  Previously this would only be true if the units were
+   'microseconds' (PR #225).  In other circumstances, as before, `cftime.date2num`
+   will return an array of floats.
+ * Rewrite of julian day/calendar functions (_IntJulianDayToCalendar and 
+   _IntJulianDayFromCalendar) to remove GPL'ed code.  cftime license
+   changed to MIT (to be consistent with netcdf4-python). 
+ * Added datetime.toordinal() (returns julian day, kwarg 'fractional'
+   can be used to include fractional day).
+ * cftime.datetime no longer uses calendar-specific sub-classes.
+
 version 1.3.1 (release tag v1.3.1rel)
 =====================================
  * fix for issue #211 (PR #212) bug in masked array handling in date2num)


=====================================
LICENSE
=====================================
@@ -0,0 +1,7 @@
+Copyright 2008 Jeffrey Whitaker
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


=====================================
MANIFEST.in
=====================================
@@ -1,6 +1,6 @@
 include *.txt
 include README.md
-include COPYING
+include LICENSE
 include pyproject.toml
 include Changelog
 exclude *.legacy


=====================================
README.md
=====================================
@@ -11,6 +11,12 @@ Time-handling functionality from netcdf4-python
 ## News
 For details on the latest updates, see the [Changelog](https://github.com/Unidata/cftime/blob/master/Changelog).
 
+2/1/2021:  Version 1.4.0 released.  License changed to MIT (GPL'ed code replaced).
+Roundtrip accuracy improved for units other than microseconds. Added 
+cftime.datetime.toordinal method, returns integer julian day number.
+
+1/17/2021: Version 1.3.1 released.
+
 11/16/2020:  Version 1.3.0 released. **API change**: The `cftime.datetime` constructor now creates 
  'calendar-aware' instances (default is `'standard'` calendar, if `calendar=''` or `None` the instance
  is not calendar aware and some methods, like `dayofwk`, `dayofyr`, `__add__` and `__sub__`, will not work)


=====================================
debian/changelog
=====================================
@@ -1,3 +1,10 @@
+cftime (1.4.0rel2+ds-1) unstable; urgency=medium
+
+  * New upstream release.
+  * Update copyright file for license change to MIT.
+
+ -- Bas Couwenberg <sebastic at debian.org>  Mon, 01 Feb 2021 05:48:54 +0100
+
 cftime (1.3.1+ds-1) unstable; urgency=medium
 
   * New upstream release.


=====================================
debian/copyright
=====================================
@@ -8,32 +8,12 @@ Files-Excluded:
 
 Files: *
 Copyright: 2008, Jeffrey Whitaker
-           2007, Michael Twomey
-           2010, David W. Pierce
-Comment: Parts of pyiso8601 are included under the MIT license.
- calendar calculation routines in _cftime.pyx derived from calcalcs.c by
- David W. Pierce, licensed under the GPL-3+.
-License: ISC and Expat and GPL-3+
+License: Expat
 
 Files: debian/*
 Copyright: 2018, Bas Couwenberg <sebastic at debian.org>
-License: ISC
+License: Expat
  
-License: ISC
- Permission to use, copy, modify, and distribute this software and
- its documentation for any purpose and without fee is hereby granted,
- provided that the above copyright notice appear in all copies and that
- both the copyright notice and this permission notice appear in
- supporting documentation.
- .
- THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
- INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO
- EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR
- CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
- USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
- PERFORMANCE OF THIS SOFTWARE.
-
 License: Expat
  Permission is hereby granted, free of charge, to any person obtaining a
  copy of this software and associated documentation files (the
@@ -53,18 +33,3 @@ License: Expat
  CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-License: GPL-3+
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
- .
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- GNU General Public License for more details.
- .
- On Debian systems, the full text of the GNU General Public License
- version 3 can be found in the file
- `/usr/share/common-licenses/GPL-3'.


=====================================
setup.py
=====================================
@@ -17,7 +17,7 @@ BASEDIR = os.path.abspath(os.path.dirname(__file__))
 SRCDIR = os.path.join(BASEDIR,'src')
 CMDS_NOCYTHONIZE = ['clean','clean_cython','sdist']
 COMPILER_DIRECTIVES = {}
-DEFINE_MACROS = None
+DEFINE_MACROS = [("NPY_NO_DEPRECATED_API", "NPY_1_7_API_VERSION")] 
 FLAG_COVERAGE = '--cython-coverage'  # custom flag enabling Cython line tracing
 NAME = 'cftime'
 CFTIME_DIR = os.path.join(SRCDIR, NAME)
@@ -78,7 +78,7 @@ if ((FLAG_COVERAGE in sys.argv or os.environ.get('CYTHON_COVERAGE', None))
                            'warn.maybe_uninitialized': False,
                            'warn.unreachable': False,
                            'warn.unused': False}
-    DEFINE_MACROS = [('CYTHON_TRACE', '1'),
+    DEFINE_MACROS += [('CYTHON_TRACE', '1'),
                      ('CYTHON_TRACE_NOGIL', '1')]
     if FLAG_COVERAGE in sys.argv:
         sys.argv.remove(FLAG_COVERAGE)
@@ -112,6 +112,7 @@ setup(
     ext_modules=ext_modules,
     install_requires=load('requirements.txt'),
     tests_require=load('requirements-dev.txt'),
+    license='License :: OSI Approved :: MIT License',
     classifiers=[
         'Development Status :: 5 - Production/Stable',
         'Operating System :: MacOS :: MacOS X',
@@ -124,5 +125,5 @@ setup(
         'Programming Language :: Python :: 3.7',
         'Programming Language :: Python :: 3.8',
         'Topic :: Scientific/Engineering',
-        'License :: OSI Approved :: GNU General Public License v3 (GPLv3)']
+        'License :: OSI Approved :: MIT License'],
     )


=====================================
src/cftime/__init__.py
=====================================
@@ -1,8 +1,10 @@
-from ._cftime import utime, JulianDayFromDate, DateFromJulianDay, UNIT_CONVERSION_FACTORS
-from ._cftime import _parse_date, date2index, time2index, datetime, real_datetime
-from ._cftime import DatetimeNoLeap, DatetimeAllLeap, Datetime360Day, DatetimeJulian, \
-                     DatetimeGregorian, DatetimeProlepticGregorian
+from ._cftime import datetime, real_datetime, _parse_date
+from ._cftime import num2date, date2num, date2index, time2index, num2pydate
 from ._cftime import microsec_units, millisec_units, \
-                     sec_units, hr_units, day_units, min_units
-from ._cftime import num2date, date2num, date2index, num2pydate
+                     sec_units, hr_units, day_units, min_units,\
+                     UNIT_CONVERSION_FACTORS
 from ._cftime import __version__
+# legacy functions in _cftime_legacy.pyx
+from ._cftime import DatetimeNoLeap, DatetimeAllLeap, Datetime360Day, DatetimeJulian, \
+                     DatetimeGregorian, DatetimeProlepticGregorian
+from ._cftime import utime, JulianDayFromDate, DateFromJulianDay


=====================================
src/cftime/_cftime.pyx
=====================================
@@ -14,10 +14,6 @@ from datetime import datetime as datetime_python
 from datetime import timedelta, MINYEAR, MAXYEAR
 import time                     # strftime
 import warnings
-try:
-    from itertools import izip as zip
-except ImportError:  # python 3.x
-    pass
 
 
 microsec_units = ['microseconds','microsecond', 'microsec', 'microsecs']
@@ -34,26 +30,18 @@ _units = microsec_units+millisec_units+sec_units+min_units+hr_units+day_units
 # for definitions.
 _calendars = ['standard', 'gregorian', 'proleptic_gregorian',
               'noleap', 'julian', 'all_leap', '365_day', '366_day', '360_day']
-# Following are number of Days Per Month
-cdef int[12] _dpm      = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
-cdef int[12] _dpm_leap = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
-cdef int[12] _dpm_360  = [30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30]
-# Same as above, but SUM of previous months (no leap years).
-cdef int[13] _spm_365day = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365]
-cdef int[13] _spm_366day = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366]
-
-# Slightly more performant cython lookups than a 2D table
-# The first 12 entries correspond to month lengths for non-leap years.
-# The remaining 12 entries give month lengths for leap years
-cdef int32_t* days_per_month_array = [
-    31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,
-    31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
+# Following are number of days per month
+cdef int[12] _dayspermonth      = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
+cdef int[12] _dayspermonth_leap = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
+# same as above, but including accumulated days of previous months.
+cdef int[13] _cumdayspermonth = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365]
+cdef int[13] _cumdayspermonth_leap = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366]
 
 # Reverse operator lookup for datetime.__richcmp__
 _rop_lookup = {Py_LT: '__gt__', Py_LE: '__ge__', Py_EQ: '__eq__',
                Py_GT: '__lt__', Py_GE: '__le__', Py_NE: '__ne__'}
 
-__version__ = '1.3.1'
+__version__ = '1.4.0'
 
 # Adapted from http://delete.me.uk/2005/03/iso8601.html
 # Note: This regex ensures that all ISO8601 timezone formats are accepted - but, due to legacy support for other timestrings, not all incorrect formats can be rejected.
@@ -67,29 +55,6 @@ ISO8601_REGEX = re.compile(r"(?P<year>[+-]?[0-9]+)(-(?P<month>[0-9]{1,2})(-(?P<d
 TIMEZONE_REGEX = re.compile(
     "(?P<prefix>[+-])(?P<hours>[0-9]{2})(?:(?::(?P<minutes1>[0-9]{2}))|(?P<minutes2>[0-9]{2}))?")
 
-
-# Taken from pandas ccalendar.pyx
- at cython.wraparound(False)
- at cython.boundscheck(False)
-cpdef int32_t get_days_in_month(bint isleap, int month) nogil:
-    """
-    Return the number of days in the given month of the given year.
-    Parameters
-    ----------
-    leap : int [0,1]
-    month : int
-
-    Returns
-    -------
-    days_in_month : int
-    Notes
-    -----
-    Assumes that the arguments are valid.  Passing a month not between 1 and 12
-    risks a segfault.
-    """
-    return days_per_month_array[12 * isleap + month - 1]
-
-
 class real_datetime(datetime_python):
     """add dayofwk, dayofyr, daysinmonth attributes to python datetime instance"""
     @property
@@ -101,7 +66,10 @@ class real_datetime(datetime_python):
         return self.timetuple().tm_yday
     @property
     def daysinmonth(self):
-        return get_days_in_month(_is_leap(self.year,'proleptic_gregorian'), self.month)
+        if _is_leap(self.year,'proleptic_gregorian'):
+            return _dayspermonth_leap[self.month-1]
+        else:
+            return _dayspermonth[self.month-1]
     nanosecond = 0 # workaround for pandas bug (cftime issue #77)
 
 def _datesplit(timestr):
@@ -237,7 +205,7 @@ def date2num(dates,units,calendar=None):
         raise ValueError("Unsupported time units provided, {!r}.".format(unit))
     if unit in ["months", "month"] and calendar != "360_day":
         raise ValueError("Units of months only valid for 360_day calendar.")
-    factor = UNIT_CONVERSION_FACTORS[unit]
+    unit_timedelta = timedelta(microseconds=UNIT_CONVERSION_FACTORS[unit])
     can_use_python_basedatetime = _can_use_python_datetime(basedate,calendar)
 
     if can_use_python_basedatetime and all_python_datetimes:
@@ -263,13 +231,12 @@ def date2num(dates,units,calendar=None):
             times.append(None)
         else:
             td = date - basedate
-            if factor == 1.0:
-                # units are microseconds, use integer division
-                times.append(td // timedelta(microseconds=1) )
+            if td % unit_timedelta == timedelta(0):
+                # Explicitly cast result to np.int64 for Windows compatibility
+                quotient = np.int64(td // unit_timedelta)
+                times.append(quotient)
             else:
-                #times.append( (td / timedelta(microseconds=1)) / factor )
-                # this appears to be faster.
-                times.append( (td.total_seconds()*1.e6) / factor )
+                times.append(td / unit_timedelta)
         n += 1
     if ismasked: # convert to masked array if input was masked array
         times = np.array(times)
@@ -328,58 +295,26 @@ UNIT_CONVERSION_FACTORS = {
     "months": 30 * 86400 * 1000000
 }
 
-
-DATE_TYPES = {
-    "proleptic_gregorian": DatetimeProlepticGregorian,
-    "standard": DatetimeGregorian,
-    "noleap": DatetimeNoLeap,
-    "365_day": DatetimeNoLeap,
-    "all_leap": DatetimeAllLeap,
-    "366_day": DatetimeAllLeap,
-    "julian": DatetimeJulian,
-    "360_day": Datetime360Day,
-    "gregorian": DatetimeGregorian
-}
-
-
-#def to_calendar_specific_datetime(dt, calendar, use_python_datetime):
-#    if use_python_datetime:
-#        return real_datetime(
-#               dt.year,
-#               dt.month,
-#               dt.day,
-#               dt.hour,
-#               dt.minute,
-#               dt.second,
-#               dt.microsecond)
-#    else:
-#        return datetime(
-#               dt.year,
-#               dt.month,
-#               dt.day,
-#               dt.hour,
-#               dt.minute,
-#               dt.second,
-#               dt.microsecond,
-#               calendar=calendar)
-# return calendar-specific subclasses for backward compatbility,
-# even though after 1.3.0 this is no longer necessary.
 def to_calendar_specific_datetime(dt, calendar, use_python_datetime):
     if use_python_datetime:
-        date_type = real_datetime
+        return real_datetime(
+               dt.year,
+               dt.month,
+               dt.day,
+               dt.hour,
+               dt.minute,
+               dt.second,
+               dt.microsecond)
     else:
-        date_type = DATE_TYPES[calendar]
-
-    return date_type(
-        dt.year,
-        dt.month,
-        dt.day,
-        dt.hour,
-        dt.minute,
-        dt.second,
-        dt.microsecond
-    )
-
+        return datetime(
+               dt.year,
+               dt.month,
+               dt.day,
+               dt.hour,
+               dt.minute,
+               dt.second,
+               dt.microsecond,
+               calendar=calendar)
 
 _MAX_INT64 = np.iinfo("int64").max
 _MIN_INT64 = np.iinfo("int64").min
@@ -985,13 +920,13 @@ The default format of the string produced by strftime is controlled by self.form
     @property
     def dayofwk(self):
         if self._dayofwk < 0 and self.calendar:
-            jd = _IntJulianDayFromDate(self.year,self.month,self.day,self.calendar,
-                                       skip_transition=False,has_year_zero=self.has_year_zero)
-            year,month,day,dayofwk,dayofyr = _IntJulianDayToDate(jd,self.calendar,
-                                       skip_transition=False,has_year_zero=self.has_year_zero)
-            # cache results for dayofwk, dayofyr
+            jd = self.toordinal()
+            dayofwk = (jd + 1) % 7
+            # convert to ISO 8601 (0 = Monday, 6 = Sunday), like python datetime
+            dayofwk -= 1
+            if dayofwk == -1: dayofwk = 6
+            # cache results for dayofwk
             self._dayofwk = dayofwk
-            self._dayofyr = dayofyr
             return dayofwk
         else:
             return self._dayofwk
@@ -999,12 +934,14 @@ The default format of the string produced by strftime is controlled by self.form
     @property
     def dayofyr(self):
         if self._dayofyr < 0 and self.calendar:
-            jd = _IntJulianDayFromDate(self.year,self.month,self.day,self.calendar,
-                                       skip_transition=False,has_year_zero=self.has_year_zero)
-            year,month,day,dayofwk,dayofyr = _IntJulianDayToDate(jd,self.calendar,
-                                       skip_transition=False,has_year_zero=self.has_year_zero)
-            # cache results for dayofwk, dayofyr
-            self._dayofwk = dayofwk
+            if self.calendar == '360_day':
+                dayofyr = (self.month-1)*30+self.day
+            else:
+                if _is_leap(self.year,self.calendar,has_year_zero=self.has_year_zero):
+                    dayofyr = _cumdayspermonth_leap[self.month-1]+self.day
+                else:
+                    dayofyr = _cumdayspermonth[self.month-1]+self.day
+            # cache results for dayofyr
             self._dayofyr = dayofyr
             return dayofyr
         else:
@@ -1012,15 +949,14 @@ The default format of the string produced by strftime is controlled by self.form
 
     @property
     def daysinmonth(self):
-        if self.calendar == 'noleap':
-            return _dpm[self.month-1]
-        elif self.calendar == 'all_leap':
-            return _dpm_leap[self.month-1]
-        elif self.calendar == '360_day':
-            return _dpm_360[self.month-1]
+        if self.calendar == '360_day':
+            return 30
         else:
-            return get_days_in_month(_is_leap(self.year,self.calendar,
-                   has_year_zero=self.has_year_zero), self.month)
+            if _is_leap(self.year,self.calendar,
+                    has_year_zero=self.has_year_zero):
+                return _dayspermonth_leap[self.month-1]
+            else:
+                return _dayspermonth[self.month-1]
 
     def strftime(self, format=None):
         """
@@ -1138,35 +1074,13 @@ The default format of the string produced by strftime is controlled by self.form
                 raise TypeError("cannot compare {0!r} and {1!r} (different calendars)".format(self, other))
             return PyObject_RichCompare(dt.to_tuple(), to_tuple(other), op)
         else:
-            # With Python3 we can simply return NotImplemented. If the other
-            # object does not support rich comparison for cftime then a
-            # TypeError will be automatically raised. However, Python2 is not
-            # consistent with this Python3 behaviour. In Python2, we only
-            # delegate the comparison operation to the other object iff it has
-            # suitable rich comparison support available. This is deduced by
-            # introspection of the other object. Otherwise, we explicitly raise
-            # a TypeError to avoid Python2 defaulting to using either __cmp__
-            # comparision on the other object, or worst still, object ID
-            # comparison. Either way, at this point the comparision is deemed
-            # not valid from our perspective.
-            if sys.version_info.major == 2:
-                rop = _rop_lookup[op]
-                if (hasattr(other, '__richcmp__') or hasattr(other, rop)):
-                    # The other object potentially has the smarts to handle
-                    # the comparision, so allow the Python machinery to hand
-                    # the operation off to the other object.
-                    return NotImplemented
-                # Otherwise, the comparison is not valid.
-                emsg = "cannot compare {0!r} and {1!r}"
-                raise TypeError(emsg.format(self, other))
-            else:
-                # Delegate responsibility of comparison to the other object.
-                return NotImplemented
+            # Delegate responsibility of comparison to the other object.
+            return NotImplemented
 
     cdef _getstate(self):
         return (self.year, self.month, self.day, self.hour,
                 self.minute, self.second, self.microsecond,
-                self._dayofwk, self._dayofyr)
+                self._dayofwk, self._dayofyr, self.calendar)
 
     def __reduce__(self):
         """special method that allows instance to be pickled"""
@@ -1175,6 +1089,31 @@ The default format of the string produced by strftime is controlled by self.form
     cdef _add_timedelta(self, other):
         return NotImplemented
 
+    def toordinal(self,fractional=False):
+        """Return julian day ordinal.
+
+        January 1 of the year -4713 is day 0 for the julian,gregorian and standard
+        calendars.
+
+        November 11 of the year -4714 is day 0 for the proleptic gregorian calendar.
+
+        January 1 of the year zero is day 0 for the 360_day, 365_day, 366_day and
+        no_leap calendars.
+        
+        If fractional=True, fractional part of day is included (default
+        False)."""
+        ijd = _IntJulianDayFromDate(self.year, self.month, self.day, self.calendar,
+               skip_transition=False,has_year_zero=self.has_year_zero)
+        if fractional:
+            fracday = self.hour / 24.0 + self.minute / 1440.0 + (self.second +
+                    self.microsecond/1.e6) / 86400.0
+            # at this point jd is an integer representing noon UTC on the given
+            # year,month,day.
+            # compute fractional day from hour,minute,second,microsecond
+            return ijd - 0.5 + fracday
+        else:
+            return ijd
+
     def __add__(self, other):
         cdef datetime dt
         if isinstance(self, datetime) and isinstance(other, timedelta):
@@ -1190,23 +1129,17 @@ The default format of the string produced by strftime is controlled by self.form
         # return calendar-specific subclasses for backward compatbility,
         # even though after 1.3.0 this is no longer necessary.
         if calendar == '360_day':
-            #return dt.__class__(*add_timedelta_360_day(dt, delta),calendar=calendar)
-            return Datetime360Day(*add_timedelta_360_day(dt, delta))
+            return dt.__class__(*add_timedelta_360_day(dt, delta),calendar=calendar)
         elif calendar == 'noleap':
-            #return dt.__class__(*add_timedelta(dt, delta, no_leap, False, True),calendar=calendar)
-            return DatetimeNoLeap(*add_timedelta(dt, delta, no_leap, False, True))
+            return dt.__class__(*add_timedelta(dt, delta, no_leap, False, True),calendar=calendar)
         elif calendar == 'all_leap':
-            #return dt.__class__(*add_timedelta(dt, delta, all_leap, False, True),calendar=calendar)
-            return DatetimeAllLeap(*add_timedelta(dt, delta, all_leap, False, True))
+            return dt.__class__(*add_timedelta(dt, delta, all_leap, False, True),calendar=calendar)
         elif calendar == 'julian':
-            #return dt.__class__(*add_timedelta(dt, delta, is_leap_julian, False, False),calendar=calendar)
-            return DatetimeJulian(*add_timedelta(dt, delta, is_leap_julian, False, False))
+            return dt.__class__(*add_timedelta(dt, delta, is_leap_julian, False, False),calendar=calendar)
         elif calendar == 'gregorian':
-            #return dt.__class__(*add_timedelta(dt, delta, is_leap_gregorian, True, False),calendar=calendar)
-            return DatetimeGregorian(*add_timedelta(dt, delta, is_leap_gregorian, True, False))
+            return dt.__class__(*add_timedelta(dt, delta, is_leap_gregorian, True, False),calendar=calendar)
         elif calendar == 'proleptic_gregorian':
-            #return dt.__class__(*add_timedelta(dt, delta, is_leap_proleptic_gregorian, False, False),calendar=calendar)
-            return DatetimeProlepticGregorian(*add_timedelta(dt, delta, is_leap_proleptic_gregorian, False, False))
+            return dt.__class__(*add_timedelta(dt, delta, is_leap_proleptic_gregorian, False, False),calendar=calendar)
         else:
             return NotImplemented
 
@@ -1220,10 +1153,8 @@ The default format of the string produced by strftime is controlled by self.form
                     raise ValueError("cannot compute the time difference between dates with different calendars")
                 if dt.calendar == "":
                     raise ValueError("cannot compute the time difference between dates that are not calendar-aware")
-                ordinal_self = _IntJulianDayFromDate(dt.year, dt.month, dt.day, dt.calendar,
-                                       skip_transition=False,has_year_zero=self.has_year_zero)
-                ordinal_other = _IntJulianDayFromDate(other.year, other.month, other.day, other.calendar,
-                                       skip_transition=False,has_year_zero=self.has_year_zero)
+                ordinal_self = self.toordinal() # julian day
+                ordinal_other = other.toordinal()
                 days = ordinal_self - ordinal_other
                 seconds_self = dt.second + 60 * dt.minute + 3600 * dt.hour
                 seconds_other = other.second + 60 * other.minute + 3600 * other.hour
@@ -1245,24 +1176,18 @@ datetime object."""
                 # return calendar-specific subclasses for backward compatbility,
                 # even though after 1.3.0 this is no longer necessary.
                 if self.calendar == '360_day':
-                    #return self.__class__(*add_timedelta_360_day(self, -other),calendar=self.calendar)
-                    return Datetime360Day(*add_timedelta_360_day(self, -other))
+                    return self.__class__(*add_timedelta_360_day(self, -other),calendar=self.calendar)
                 elif self.calendar == 'noleap':
-                    #return self.__class__(*add_timedelta(self, -other, no_leap, False, True),calendar=self.calendar)
-                    return DatetimeNoLeap(*add_timedelta(self, -other, no_leap, False, True))
+                    return self.__class__(*add_timedelta(self, -other, no_leap, False, True),calendar=self.calendar)
                 elif self.calendar == 'all_leap':
-                    #return self.__class__(*add_timedelta(self, -other, all_leap, False, True),calendar=self.calendar)
-                    return DatetimeAllLeap(*add_timedelta(self, -other, all_leap, False, True))
+                    return self.__class__(*add_timedelta(self, -other, all_leap, False, True),calendar=self.calendar)
                 elif self.calendar == 'julian':
-                    #return self.__class__(*add_timedelta(self, -other, is_leap_julian, False, False),calendar=self.calendar)
-                    return DatetimeJulian(*add_timedelta(self, -other, is_leap_julian, False, False))
+                    return self.__class__(*add_timedelta(self, -other, is_leap_julian, False, False),calendar=self.calendar)
                 elif self.calendar == 'gregorian':
-                    #return self.__class__(*add_timedelta(self, -other, is_leap_gregorian, True, False),calendar=self.calendar)
-                    return DatetimeGregorian(*add_timedelta(self, -other, is_leap_gregorian, True, False))
+                    return self.__class__(*add_timedelta(self, -other, is_leap_gregorian, True, False),calendar=self.calendar)
                 elif self.calendar == 'proleptic_gregorian':
-                    #return self.__class__(*add_timedelta(self, -other,
-                    #    is_leap_proleptic_gregorian, False, False),calendar=self.calendar)
-                    return DatetimeProlepticGregorian(*add_timedelta(self, -other, is_leap_proleptic_gregorian, False, False))
+                    return self.__class__(*add_timedelta(self, -other,
+                        is_leap_proleptic_gregorian, False, False),calendar=self.calendar)
                 else:
                     return NotImplemented
             else:
@@ -1281,113 +1206,6 @@ datetime object."""
             else:
                 return NotImplemented
 
-# these calendar-specific sub-classes are no longer used, but stubs
-# remain for backward compatibility.
-
- at cython.embedsignature(True)
-cdef class DatetimeNoLeap(datetime):
-    """
-Phony datetime object which mimics the python datetime object,
-but uses the "noleap" ("365_day") calendar.
-    """
-    def __init__(self, *args, **kwargs):
-        kwargs['calendar']='noleap'
-        super().__init__(*args, **kwargs)
-    def __repr__(self):
-        return "{0}.{1}({2}, {3}, {4}, {5}, {6}, {7}, {8})".format('cftime',
-                                     self.__class__.__name__,
-                                     self.year,self.month,self.day,self.hour,self.minute,self.second,self.microsecond)
-
- at cython.embedsignature(True)
-cdef class DatetimeAllLeap(datetime):
-    """
-Phony datetime object which mimics the python datetime object,
-but uses the "all_leap" ("366_day") calendar.
-    """
-    def __init__(self, *args, **kwargs):
-        kwargs['calendar']='all_leap'
-        super().__init__(*args, **kwargs)
-    def __repr__(self):
-        return "{0}.{1}({2}, {3}, {4}, {5}, {6}, {7}, {8})".format('cftime',
-                                     self.__class__.__name__,
-                                     self.year,self.month,self.day,self.hour,self.minute,self.second,self.microsecond)
-
- at cython.embedsignature(True)
-cdef class Datetime360Day(datetime):
-    """
-Phony datetime object which mimics the python datetime object,
-but uses the "360_day" calendar.
-    """
-    def __init__(self, *args, **kwargs):
-        kwargs['calendar']='360_day'
-        super().__init__(*args, **kwargs)
-    def __repr__(self):
-        return "{0}.{1}({2}, {3}, {4}, {5}, {6}, {7}, {8})".format('cftime',
-                                     self.__class__.__name__,
-                                     self.year,self.month,self.day,self.hour,self.minute,self.second,self.microsecond)
-
- at cython.embedsignature(True)
-cdef class DatetimeJulian(datetime):
-    """
-Phony datetime object which mimics the python datetime object,
-but uses the "julian" calendar.
-    """
-    def __init__(self, *args, **kwargs):
-        kwargs['calendar']='julian'
-        super().__init__(*args, **kwargs)
-    def __repr__(self):
-        return "{0}.{1}({2}, {3}, {4}, {5}, {6}, {7}, {8})".format('cftime',
-                                     self.__class__.__name__,
-                                     self.year,self.month,self.day,self.hour,self.minute,self.second,self.microsecond)
-
- at cython.embedsignature(True)
-cdef class DatetimeGregorian(datetime):
-    """
-Phony datetime object which mimics the python datetime object,
-but uses the mixed Julian-Gregorian ("standard", "gregorian") calendar.
-
-The last date of the Julian calendar is 1582-10-4, which is followed
-by 1582-10-15, using the Gregorian calendar.
-
-Instances using the date after 1582-10-15 can be compared to
-datetime.datetime instances and used to compute time differences
-(datetime.timedelta) by subtracting a DatetimeGregorian instance from
-a datetime.datetime instance or vice versa.
-    """
-    def __init__(self, *args, **kwargs):
-        kwargs['calendar']='gregorian'
-        super().__init__(*args, **kwargs)
-    def __repr__(self):
-        return "{0}.{1}({2}, {3}, {4}, {5}, {6}, {7}, {8})".format('cftime',
-                                     self.__class__.__name__,
-                                     self.year,self.month,self.day,self.hour,self.minute,self.second,self.microsecond)
-
- at cython.embedsignature(True)
-cdef class DatetimeProlepticGregorian(datetime):
-    """
-Phony datetime object which mimics the python datetime object,
-but allows for dates that don't exist in the proleptic gregorian calendar.
-
-Supports timedelta operations by overloading + and -.
-
-Has strftime, timetuple, replace, __repr__, and __str__ methods. The
-format of the string produced by __str__ is controlled by self.format
-(default %Y-%m-%d %H:%M:%S). Supports comparisons with other
-datetime instances using the same calendar; comparison with
-native python datetime instances is possible for cftime.datetime
-instances using 'gregorian' and 'proleptic_gregorian' calendars.
-
-Instance variables are year,month,day,hour,minute,second,microsecond,dayofwk,dayofyr,
-format, and calendar.
-    """
-    def __init__(self, *args, **kwargs):
-        kwargs['calendar']='proleptic_gregorian'
-        super().__init__( *args, **kwargs)
-    def __repr__(self):
-        return "{0}.{1}({2}, {3}, {4}, {5}, {6}, {7}, {8})".format('cftime',
-                                     self.__class__.__name__,
-                                     self.year,self.month,self.day,self.hour,self.minute,self.second,self.microsecond)
-
 _illegal_s = re.compile(r"((^|[^%])(%%)*%s)")
 
 
@@ -1464,9 +1282,9 @@ cdef bint no_leap(int year):
 
 cdef int * month_lengths(bint (*is_leap)(int), int year):
     if is_leap(year):
-        return _dpm_leap
+        return _dayspermonth_leap
     else:
-        return _dpm
+        return _dayspermonth
 
 cdef void assert_valid_date(datetime dt, bint (*is_leap)(int),
                             bint julian_gregorian_mixed,
@@ -1478,7 +1296,7 @@ cdef void assert_valid_date(datetime dt, bint (*is_leap)(int),
         if dt.year == 0:
             raise ValueError("invalid year provided in {0!r}".format(dt))
     if is_360_day:
-        month_length = _dpm_360
+        month_length = 12*[30]
     else:
         month_length = month_lengths(is_leap, dt.year)
 
@@ -1633,9 +1451,6 @@ cdef tuple add_timedelta_360_day(datetime dt, delta):
 
     return (year, month, day, hour, minute, second, microsecond, -1, -1)
 
-# Calendar calculations base on calcals.c by David W. Pierce
-# http://meteora.ucsd.edu/~pierce/calcalcs
-
 cdef _is_leap(int year, calendar, has_year_zero=False):
     cdef int tyear
     cdef bint leap
@@ -1666,6 +1481,27 @@ cdef _is_leap(int year, calendar, has_year_zero=False):
         leap = False
     return leap
 
+cdef _check_calendar(calendar):
+    """validate calendars, convert to subset of names to get rid of synonyms"""
+    if calendar not in _calendars:
+        raise ValueError('unsupported calendar')
+    calout = calendar
+    # remove 'gregorian','noleap','all_leap'
+    if calendar in 'gregorian':
+        calout = 'standard'
+    if calendar == 'noleap':
+        calout = '365_day'
+    if calendar == 'all_leap':
+        calout = '366_day'
+    return calout
+
+# The following function (_IntJulianDayFromDate) is based on
+# algorithms described in the book
+# "Calendrical Calculations" by Dershowitz and Rheingold, 3rd edition, Cambridge University Press, 2007
+# and the C implementation provided at https://reingold.co/calendar.C
+# with modifications to handle non-real-world calendars and negative years.
+
+
 cdef _IntJulianDayFromDate(int year,int month,int day,calendar,skip_transition=False,has_year_zero=False):
     """Compute integer Julian Day from year,month,day and calendar.
 
@@ -1698,7 +1534,6 @@ cdef _IntJulianDayFromDate(int year,int month,int day,calendar,skip_transition=F
     unless calendar = 'standard'."""
     cdef int jday, jday_jul, jday_greg
     cdef bint leap
-    cdef int[12] dpm2use
 
     # validate inputs.
     calendar = _check_calendar(calendar)
@@ -1707,49 +1542,47 @@ cdef _IntJulianDayFromDate(int year,int month,int day,calendar,skip_transition=F
         (year,month,day,calendar)
         raise ValueError(msg)
 
-    # handle all calendars except standard, julian, proleptic_gregorian.
     if calendar == '360_day':
-        return _IntJulianDayFromDate_360day(year,month,day)
+        return year*360 + (month-1)*30 + day - 1
     elif calendar == '365_day':
-        return _IntJulianDayFromDate_365day(year,month,day)
+        if month == 2 and day == 29:
+            raise ValueError('no leap days in 365_day calendar')
+        return year*365 + _cumdayspermonth[month-1] + day - 1
     elif calendar == '366_day':
-        return _IntJulianDayFromDate_366day(year,month,day)
+        return year*366 + _cumdayspermonth_leap[month-1] + day - 1
 
     # handle standard, julian, proleptic_gregorian calendars.
     if year == 0 and not has_year_zero:
         raise ValueError('year zero does not exist in the %s calendar' %\
                 calendar)
-    if (calendar == 'proleptic_gregorian'         and year < -4714) or\
+    if (calendar == 'proleptic_gregorian'  and year < -4714) or\
        (calendar in ['julian','standard']  and year < -4713):
         raise ValueError('year out of range for %s calendar' % calendar)
     leap = _is_leap(year,calendar,has_year_zero=has_year_zero)
     if not leap and month == 2 and day == 29:
         raise ValueError('%s is not a leap year' % year)
 
-    # add year offset
-    if year < 0 and not has_year_zero:
-        year += 4801
-    else:
-        year += 4800
-
     if leap:
-        dpm2use = _dpm_leap
+        jday = day + _cumdayspermonth_leap[month-1]
     else:
-        dpm2use = _dpm
-
-    jday = day
-    for m in range(month-1,0,-1):
-        jday += dpm2use[m-1]
-
-    jday_greg = jday + 365*(year-1) + (year-1)//4 - (year-1)//100 + (year-1)//400
-    jday_greg -= 31739 # fix year offset
+        jday = day + _cumdayspermonth[month-1]
+    if year < 0 and not has_year_zero: year += 1
+    year += 4800 # add offset so -4800 is year 0.
+    # 1st term is the number of days in the last year
+    # 2nd term is the number of days in each preceding non-leap year
+    # last terms are the number of preceding leap years since -4800
     jday_jul = jday + 365*(year-1) + (year-1)//4
-    jday_jul -= 31777 # fix year offset
+    # remove offset for 87 years before -4713 (including leap days)
+    jday_jul -= 31777
+    jday_greg = jday + 365*(year-1) + (year-1)//4 - (year-1)//100 + (year-1)//400
+    # remove offset, and account for the fact that -4713/1/1 is jday=38 in
+    # gregorian calendar.
+    jday_greg -= 31739
     if calendar == 'julian':
         return jday_jul
     elif calendar == 'proleptic_gregorian':
         return jday_greg
-    elif calendar == 'standard':
+    elif calendar in ['standard','gregorian']:
         # check for invalid days in mixed calendar (there are 10 missing)
         if jday_jul >= 2299161 and jday_jul < 2299171:
             raise ValueError('invalid date in mixed calendar')
@@ -1761,567 +1594,5 @@ cdef _IntJulianDayFromDate(int year,int month,int day,calendar,skip_transition=F
             else:
                 return jday_greg
 
-    return jday
-
-cdef _IntJulianDayToDate(int jday,calendar,skip_transition=False,has_year_zero=False):
-    """Compute the year,month,day,dow,doy given the integer Julian day.
-    and calendar. (dow = day of week with 0=Mon,6=Sun and doy is day of year).
-
-    Allowed calendars are 'standard', 'gregorian', 'julian',
-    'proleptic_gregorian','360_day', '365_day', '366_day', 'noleap',
-    'all_leap'.
-
-    'noleap' is a synonym for '365_day'
-    'all_leap' is a synonym for '366_day'
-    'gregorian' is a synonym for 'standard'
-
-    optional kwarg 'skip_transition':  When True, assume a 10-day
-    gap in Julian day numbers between Oct 4 and Oct 15 1582 (the transition
-    from Julian to Gregorian calendars).  Default False, ignored
-    unless calendar = 'standard'."""
-    cdef int year,month,day,dow,doy,yp1,tjday
-    cdef int[12] dpm2use
-    cdef int[13] spm2use
-
-    # validate inputs.
-    calendar = _check_calendar(calendar)
-
-    # handle all calendars except standard, julian, proleptic_gregorian.
-    if calendar == '360_day':
-        return _IntJulianDayToDate_360day(jday)
-    elif calendar == '365_day':
-        return _IntJulianDayToDate_365day(jday)
-    elif calendar == '366_day':
-        return _IntJulianDayToDate_366day(jday)
-
-    # handle standard, julian, proleptic_gregorian calendars.
-    if jday < 0:
-        raise ValueError('julian day must be a positive integer')
-    # Make first estimate for year. subtract 4714 or 4713 because Julian Day number
-    # 0 occurs in year 4714 BC in the Gregorian calendar and 4713 BC in the
-    # Julian calendar.
-    if calendar == 'proleptic_gregorian':
-        year = jday//366 - 4714
-    elif calendar in ['standard','julian']:
-        year = jday//366 - 4713
-
-    # compute day of week.
-    dow = _get_dow(jday)
-
-    if not skip_transition and calendar == 'standard' and jday > 2299160: jday += 10
-
-    # Advance years until we find the right one
-    yp1 = year + 1
-    if yp1 == 0 and not has_year_zero:
-       yp1 = 1 # no year 0
-    tjday = _IntJulianDayFromDate(yp1,1,1,calendar,skip_transition=True,has_year_zero=has_year_zero)
-    while jday >= tjday:
-        year += 1
-        if year == 0 and not has_year_zero:
-            year = 1
-        yp1 = year + 1
-        if yp1 == 0 and not has_year_zero:
-            yp1 = 1
-        tjday = _IntJulianDayFromDate(yp1,1,1,calendar,skip_transition=True,has_year_zero=has_year_zero)
-    if _is_leap(year, calendar,has_year_zero=has_year_zero):
-        dpm2use = _dpm_leap
-        spm2use = _spm_366day
-    else:
-        dpm2use = _dpm
-        spm2use = _spm_365day
-    month = 1
-    tjday =\
-    _IntJulianDayFromDate(year,month,dpm2use[month-1],calendar,skip_transition=True,has_year_zero=has_year_zero)
-    while jday > tjday:
-        month += 1
-        tjday =\
-        _IntJulianDayFromDate(year,month,dpm2use[month-1],calendar,skip_transition=True,has_year_zero=has_year_zero)
-    tjday = _IntJulianDayFromDate(year,month,1,calendar,skip_transition=True,has_year_zero=has_year_zero)
-    day = jday - tjday + 1
-    if month == 1:
-        doy = day
-    else:
-        doy = spm2use[month-1]+day
-    return year,month,day,dow,doy
-
-cdef _get_dow(int jday):
-    """compute day of week.
-    0 = Sunday, 6 = Sat, valid after noon UTC"""
-    cdef int dow
-    dow = (jday + 1) % 7
-    # convert to ISO 8601 (0 = Monday, 6 = Sunday), like python datetime
-    dow -= 1
-    if dow == -1: dow = 6
-    return dow
-
-cdef _check_calendar(calendar):
-    """validate calendars, convert to subset of names to get rid of synonyms"""
-    if calendar not in _calendars:
-        raise ValueError('unsupported calendar')
-    calout = calendar
-    # remove 'gregorian','noleap','all_leap'
-    if calendar in ['gregorian','standard']:
-        calout = 'standard'
-    if calendar == 'noleap':
-        calout = '365_day'
-    if calendar == 'all_leap':
-        calout = '366_day'
-    return calout
-
-cdef _IntJulianDayFromDate_360day(int year,int month,int day):
-    """Compute integer Julian Day from year,month,day in
-    360_day calendar"""
-    return year*360 + (month-1)*30 + day - 1
-
-cdef _IntJulianDayFromDate_365day(int year,int month,int day):
-    """Compute integer Julian Day from year,month,day in
-    365_day calendar"""
-    if month == 2 and day == 29:
-        raise ValueError('no leap days in 365_day calendar')
-    return year*365 + _spm_365day[month-1] + day - 1
-
-cdef _IntJulianDayFromDate_366day(int year,int month,int day):
-    """Compute integer Julian Day from year,month,day in
-    366_day calendar"""
-    return year*366 + _spm_366day[month-1] + day - 1
-
-cdef _IntJulianDayToDate_365day(int jday):
-    """Compute the year,month,day given the integer Julian day
-    for 365_day calendar."""
-    cdef int year,month,day,nextra,dow
-
-    year = jday//365
-    nextra = jday - year*365
-    doy    = nextra + 1 # Julday numbering starts at 0, doy starts at 1
-    month = 1
-    while doy > _spm_365day[month]:
-        month += 1
-    day = doy - _spm_365day[month-1]
-
-    # compute day of week.
-    dow = _get_dow(jday)
-
-    return year,month,day,dow,doy
-
-cdef _IntJulianDayToDate_366day(int jday):
-    """Compute the year,month,day given the integer Julian day
-    for 366_day calendar."""
-    cdef int year,month,day,nextra,dow
-
-    year = jday//366
-    nextra = jday - year*366
-    doy    = nextra + 1 # Julday numbering starts at 0, doy starts at 1
-    month = 1
-    while doy > _spm_366day[month]:
-        month += 1
-    day = doy - _spm_366day[month-1]
-
-    # compute day of week.
-    dow = _get_dow(jday)
-
-    return year,month,day,dow,doy
-
-cdef _IntJulianDayToDate_360day(int jday):
-    """Compute the year,month,day given the integer Julian day
-    for 360_day calendar."""
-    cdef int year,month,day,nextra,dow
-
-    year = jday//360
-    nextra = jday - year*360
-    doy    = nextra + 1 # Julday numbering starts at 0, doy starts at 1
-    month = nextra//30 + 1
-    day   = doy - (month-1)*30
-
-    # compute day of week.
-    dow = _get_dow(jday)
-
-    return year,month,day,dow,doy
-
-# stuff below no longer used, kept here for backwards compatibility.
-
-def _round_half_up(x):
-    # 'round half up' so 0.5 rounded to 1 (instead of 0 as in numpy.round)
-    return np.ceil(np.floor(2.*x)/2.)
-
- at cython.embedsignature(True)
-def JulianDayFromDate(date, calendar='standard'):
-    """JulianDayFromDate(date, calendar='standard')
-
-    creates a Julian Day from a 'datetime-like' object.  Returns the fractional
-    Julian Day (approximately 100 microsecond accuracy).
-
-    if calendar='standard' or 'gregorian' (default), Julian day follows Julian
-    Calendar on and before 1582-10-5, Gregorian calendar after 1582-10-15.
-
-    if calendar='proleptic_gregorian', Julian Day follows gregorian calendar.
-
-    if calendar='julian', Julian Day follows julian calendar.
-    """
-
-    # check if input was scalar and change return accordingly
-    isscalar = False
-    try:
-        date[0]
-    except:
-        isscalar = True
-
-    date = np.atleast_1d(np.array(date))
-    year = np.empty(len(date), dtype=np.int32)
-    month = year.copy()
-    day = year.copy()
-    hour = year.copy()
-    minute = year.copy()
-    second = year.copy()
-    microsecond = year.copy()
-    jd = np.empty(year.shape, np.longdouble)
-    cdef long double[:] jd_view = jd
-    cdef Py_ssize_t i_max = len(date)
-    cdef Py_ssize_t i
-    for i in range(i_max):
-        d = date[i]
-        if getattr(d, 'tzinfo', None) is not None:
-            d = d.replace(tzinfo=None) - d.utcoffset()
-
-        year[i] = d.year
-        month[i] = d.month
-        day[i] = d.day
-        hour[i] = d.hour
-        minute[i] = d.minute
-        second[i] = d.second
-        microsecond[i] = d.microsecond
-        jd_view[i] = <double>_IntJulianDayFromDate(<int>year[i],<int>month[i],<int>day[i],calendar)
-
-    # at this point jd is an integer representing noon UTC on the given
-    # year,month,day.
-    # compute fractional day from hour,minute,second,microsecond
-    fracday = hour / 24.0 + minute / 1440.0 + (second + microsecond/1.e6) / 86400.0
-    jd = jd - 0.5 + fracday
-
-    if isscalar:
-        return jd[0]
-    else:
-        return jd
-
- at cython.embedsignature(True)
-def DateFromJulianDay(JD, calendar='standard', only_use_cftime_datetimes=True,
-                      return_tuple=False):
-    """
-
-    returns a 'datetime-like' object given Julian Day. Julian Day is a
-    fractional day with approximately 100 microsecond accuracy.
-
-    if calendar='standard' or 'gregorian' (default), Julian day follows Julian
-    Calendar on and before 1582-10-5, Gregorian calendar after  1582-10-15.
-
-    if calendar='proleptic_gregorian', Julian Day follows gregorian calendar.
-
-    if calendar='julian', Julian Day follows julian calendar.
-
-    If only_use_cftime_datetimes is set to True, then cftime.datetime
-    objects are returned for all calendars.  Otherwise the datetime object is a
-    native python datetime object if the date falls in the Gregorian calendar
-    (i.e. calendar='proleptic_gregorian', or  calendar = 'standard'/'gregorian'
-    and the date is after 1582-10-15).
-    """
-
-    julian = np.atleast_1d(np.array(JD, dtype=np.longdouble))
-
-    def getdateinfo(julian):
-        # get the day (Z) and the fraction of the day (F)
-        # use 'round half up' rounding instead of numpy's even rounding
-        # so that 0.5 is rounded to 1.0, not 0 (cftime issue #49)
-        Z = np.atleast_1d(np.int32(_round_half_up(julian)))
-        F = (julian + 0.5 - Z).astype(np.longdouble)
-
-        cdef Py_ssize_t i_max = len(Z)
-        year = np.empty(i_max, dtype=np.int32)
-        month = np.empty(i_max, dtype=np.int32)
-        day = np.empty(i_max, dtype=np.int32)
-        dayofyr = np.zeros(i_max,dtype=np.int32)
-        dayofwk = np.zeros(i_max,dtype=np.int32)
-        cdef int ijd
-        cdef Py_ssize_t i
-        for i in range(i_max):
-            ijd = Z[i]
-            year[i],month[i],day[i],dayofwk[i],dayofyr[i] = _IntJulianDayToDate(ijd,calendar)
-
-        if calendar in ['standard', 'gregorian']:
-            ind_before = np.where(julian < 2299160.5)
-            ind_before = np.asarray(ind_before).any()
-        else:
-            ind_before = False
-
-        # compute hour, minute, second, microsecond, convert to int32
-        hour = np.clip((F * 24.).astype(np.int64), 0, 23)
-        F   -= hour / 24.
-        minute = np.clip((F * 1440.).astype(np.int64), 0, 59)
-        second = np.clip((F - minute / 1440.) * 86400., 0, None)
-        microsecond = (second % 1)*1.e6
-        hour = hour.astype(np.int32)
-        minute = minute.astype(np.int32)
-        second = second.astype(np.int32)
-        microsecond = microsecond.astype(np.int32)
-
-        return year,month,day,hour,minute,second,microsecond,dayofyr,dayofwk,ind_before
-
-    year,month,day,hour,minute,second,microsecond,dayofyr,dayofwk,ind_before =\
-    getdateinfo(julian)
-    # round to nearest second if within ms_eps microseconds
-    # (to avoid ugly errors in datetime formatting - alternative
-    # to adding small offset all the time as was done previously)
-    # see netcdf4-python issue #433 and cftime issue #78
-    # this is done by rounding microsends up or down, then
-    # recomputing year,month,day etc
-    # ms_eps is proportional to julian day,
-    # about 47 microseconds in 2000 for Julian base date in -4713
-    ms_eps = np.atleast_1d(np.array(np.finfo(np.float64).eps,np.longdouble))
-    ms_eps = 86400000000.*np.maximum(ms_eps*julian, ms_eps)
-    microsecond = np.where(microsecond < ms_eps, 0, microsecond)
-    indxms = microsecond > 1000000-ms_eps
-    if indxms.any():
-        julian[indxms] = julian[indxms] + 2*ms_eps[indxms]/86400000000..
-        year[indxms],month[indxms],day[indxms],hour[indxms],minute[indxms],second[indxms],microsecond2,dayofyr[indxms],dayofwk[indxms],ind_before2 =\
-        getdateinfo(julian[indxms])
-        microsecond[indxms] = 0
-
-    # check if input was scalar and change return accordingly
-    isscalar = False
-    try:
-        JD[0]
-    except:
-        isscalar = True
-
-    if calendar == 'proleptic_gregorian':
-        # datetime.datetime does not support years < 1
-        #if year < 0:
-        if only_use_cftime_datetimes:
-            datetime_type = DatetimeProlepticGregorian
-        else:
-            if (year < 0).any(): # netcdftime issue #28
-               datetime_type = DatetimeProlepticGregorian
-            else:
-               datetime_type = real_datetime
-    elif calendar in ('standard', 'gregorian'):
-        # return a 'real' datetime instance if calendar is proleptic
-        # Gregorian or Gregorian and all dates are after the
-        # Julian/Gregorian transition
-        if ind_before and not only_use_cftime_datetimes:
-            datetime_type = real_datetime
-        else:
-            datetime_type = DatetimeGregorian
-    elif calendar == "julian":
-        datetime_type = DatetimeJulian
-    elif calendar in ["noleap","365_day"]:
-        datetime_type = DatetimeNoLeap
-    elif calendar in ["all_leap","366_day"]:
-        datetime_type = DatetimeAllLeap
-    elif calendar == "360_day":
-        datetime_type = Datetime360Day
-    else:
-        raise ValueError("unsupported calendar: {0}".format(calendar))
-
-    if not isscalar:
-        if return_tuple:
-            return np.array([args for args in
-                            zip(year, month, day, hour, minute, second,
-                                microsecond,dayofwk,dayofyr)])
-        else:
-            return np.array([datetime_type(*args)
-                             for args in
-                             zip(year, month, day, hour, minute, second,
-                                 microsecond)])
-
-    else:
-        if return_tuple:
-            return (year[0], month[0], day[0], hour[0],
-                    minute[0], second[0], microsecond[0],
-                    dayofwk[0], dayofyr[0])
-        else:
-            return datetime_type(year[0], month[0], day[0], hour[0],
-                                 minute[0], second[0], microsecond[0])
-
-class utime:
-
-    """
-Performs conversions of netCDF time coordinate
-data to/from datetime objects.
-
-To initialize: `t = utime(unit_string,calendar='standard'`
-
-where
-
-`unit_string` is a string of the form
-`time-units since <time-origin>` defining the time units.
-
-Valid time-units are days, hours, minutes and seconds (the singular forms
-are also accepted). An example unit_string would be `hours
-since 0001-01-01 00:00:00`. months is allowed as a time unit
-*only* for the 360_day calendar.
-
-The calendar keyword describes the calendar used in the time calculations.
-All the values currently defined in the U{CF metadata convention
-<http://cf-pcmdi.llnl.gov/documents/cf-conventions/1.1/cf-conventions.html#time-coordinate>}
-are accepted. The default is 'standard', which corresponds to the mixed
-Gregorian/Julian calendar used by the udunits library. Valid calendars
-are:
-
-'gregorian' or 'standard' (default):
-
-Mixed Gregorian/Julian calendar as defined by udunits.
-
-'proleptic_gregorian':
-
-A Gregorian calendar extended to dates before 1582-10-15. That is, a year
-is a leap year if either (i) it is divisible by 4 but not by 100 or (ii)
-it is divisible by 400.
-
-'noleap' or '365_day':
-
-Gregorian calendar without leap years, i.e., all years are 365 days long..
-all_leap or 366_day Gregorian calendar with every year being a leap year,
-i.e., all years are 366 days long.
-
-'360_day':
-
-All years are 360 days divided into 30 day months.
-
-'julian':
-
-Proleptic Julian calendar, extended to dates after 1582-10-5. A year is a
-leap year if it is divisible by 4.
-
-The num2date and date2num class methods can used to convert datetime
-instances to/from the specified time units using the specified calendar.
-
-Example usage:
-
->>> from cftime import utime
->>> from datetime import  datetime
->>> cdftime = utime('hours since 0001-01-01 00:00:00')
->>> date = datetime.now()
->>> print date
-2016-10-05 08:46:27.245015
->>>
->>> t = cdftime.date2num(date)
->>> print t
-17669840.7742
->>>
->>> date = cdftime.num2date(t)
->>> print date
-2016-10-05 08:46:27.244996
->>>
-
-The resolution of the transformation operation is approximately a microsecond.
-
-Warning:  Dates between 1582-10-5 and 1582-10-15 do not exist in the
-'standard' or 'gregorian' calendars.  An exception will be raised if you pass
-a 'datetime-like' object in that range to the date2num class method.
-
-Words of Wisdom from the British MetOffice concerning reference dates:
-
-"udunits implements the mixed Gregorian/Julian calendar system, as
-followed in England, in which dates prior to 1582-10-15 are assumed to use
-the Julian calendar. Other software cannot be relied upon to handle the
-change of calendar in the same way, so for robustness it is recommended
-that the reference date be later than 1582. If earlier dates must be used,
-it should be noted that udunits treats 0 AD as identical to 1 AD."
-
- at ivar origin: datetime instance defining the origin of the netCDF time variable.
- at ivar calendar:  the calendar used (as specified by the `calendar` keyword).
- at ivar unit_string:  a string defining the the netCDF time variable.
- at ivar units:  the units part of `unit_string` (i.e. 'days', 'hours', 'seconds').
-    """
-
-    def __init__(self, unit_string, calendar='standard',
-                 only_use_cftime_datetimes=True,only_use_python_datetimes=False):
-        """
- at param unit_string: a string of the form
-`time-units since <time-origin>` defining the time units.
-
-Valid time-units are days, hours, minutes and seconds (the singular forms
-are also accepted). An example unit_string would be `hours
-since 0001-01-01 00:00:00`. months is allowed as a time unit
-*only* for the 360_day calendar.
-
- at keyword calendar: describes the calendar used in the time calculations.
-All the values currently defined in the U{CF metadata convention
-<http://cf-pcmdi.llnl.gov/documents/cf-conventions/1.1/cf-conventions.html#time-coordinate>}
-are accepted. The default is `standard`, which corresponds to the mixed
-Gregorian/Julian calendar used by the udunits library. Valid calendars
-are:
- - `gregorian` or `standard` (default):
- Mixed Gregorian/Julian calendar as defined by udunits.
- - `proleptic_gregorian`:
- A Gregorian calendar extended to dates before 1582-10-15. That is, a year
- is a leap year if either (i) it is divisible by 4 but not by 100 or (ii)
- it is divisible by 400.
- - `noleap` or `365_day`:
- Gregorian calendar without leap years, i.e., all years are 365 days long.
- - `all_leap` or `366_day`:
- Gregorian calendar with every year being a leap year, i.e.,
- all years are 366 days long.
- -`360_day`:
- All years are 360 days divided into 30 day months.
- -`julian`:
- Proleptic Julian calendar, extended to dates after 1582-10-5. A year is a
- leap year if it is divisible by 4.
-
- at keyword only_use_cftime_datetimes: if False, datetime.datetime
-objects are returned from num2date where possible; if True dates which subclass
-cftime.datetime are returned for all calendars. Default True.
-
- at keyword only_use_python_datetimes: always return python datetime.datetime
-objects and raise an error if this is not possible. Ignored unless
-**only_use_cftime_datetimes=False**. Default **False**.
-
- at returns: A class instance which may be used for converting times from netCDF
-units to datetime objects.
-        """
-        calendar = calendar.lower()
-        if calendar in _calendars:
-            self.calendar = calendar
-        else:
-            raise ValueError(
-                "calendar must be one of %s, got '%s'" % (str(_calendars), calendar))
-        self.origin = _dateparse(unit_string,calendar=calendar)
-        units, isostring = _datesplit(unit_string)
-        self.units = units
-        self.unit_string = unit_string
-        self.only_use_cftime_datetimes = only_use_cftime_datetimes
-        self.only_use_python_datetimes = only_use_python_datetimes
-
-    def date2num(self, date):
-        """
-        Returns `time_value` in units described by `unit_string`, using
-        the specified `calendar`, given a 'datetime-like' object.
-
-        The datetime object must represent UTC with no time-zone offset.
-        If there is a time-zone offset implied by L{unit_string}, it will
-        be applied to the returned numeric values.
-
-        Resolution is approximately a microsecond.
-
-        If calendar = 'standard' or 'gregorian' (indicating
-        that the mixed Julian/Gregorian calendar is to be used), an
-        exception will be raised if the 'datetime-like' object describes
-        a date between 1582-10-5 and 1582-10-15.
-
-        Works for scalars, sequences and numpy arrays.
-        Returns a scalar if input is a scalar, else returns a numpy array.
-        """
-        return date2num(date,self.unit_string,calendar=self.calendar)
-
-    def num2date(self, time_value):
-        """
-        Return a 'datetime-like' object given a `time_value` in units
-        described by `unit_string`, using `calendar`.
-
-        dates are in UTC with no offset, even if L{unit_string} contains
-        a time zone offset from UTC.
-
-        Resolution is approximately a microsecond.
-
-        Works for scalars, sequences and numpy arrays.
-        Returns a scalar if input is a scalar, else returns a numpy array.
-        """
-        return num2date(time_value,self.unit_string,calendar=self.calendar,only_use_cftime_datetimes=self.only_use_cftime_datetimes,only_use_python_datetimes=self.only_use_python_datetimes)
+# include legacy stuff no longer used by cftime.datetime
+include "_cftime_legacy.pyx"


=====================================
src/cftime/_cftime_legacy.pyx
=====================================
@@ -0,0 +1,633 @@
+# stuff below no longer used by cftime.datetime, kept here for backwards compatibility.
+
+ at cython.embedsignature(True)
+cdef class DatetimeNoLeap(datetime):
+    """
+Phony datetime object which mimics the python datetime object,
+but uses the "noleap" ("365_day") calendar.
+    """
+    def __init__(self, *args, **kwargs):
+        kwargs['calendar']='noleap'
+        super().__init__(*args, **kwargs)
+    def __repr__(self):
+        return "{0}.{1}({2}, {3}, {4}, {5}, {6}, {7}, {8})".format('cftime',
+        self.__class__.__name__,
+        self.year,self.month,self.day,self.hour,self.minute,self.second,self.microsecond)
+    cdef _getstate(self):
+        return (self.year, self.month, self.day, self.hour,
+                self.minute, self.second, self.microsecond,
+                self._dayofwk, self._dayofyr)
+
+ at cython.embedsignature(True)
+cdef class DatetimeAllLeap(datetime):
+    """
+Phony datetime object which mimics the python datetime object,
+but uses the "all_leap" ("366_day") calendar.
+    """
+    def __init__(self, *args, **kwargs):
+        kwargs['calendar']='all_leap'
+        super().__init__(*args, **kwargs)
+    def __repr__(self):
+        return "{0}.{1}({2}, {3}, {4}, {5}, {6}, {7}, {8})".format('cftime',
+        self.__class__.__name__,
+        self.year,self.month,self.day,self.hour,self.minute,self.second,self.microsecond)
+    cdef _getstate(self):
+        return (self.year, self.month, self.day, self.hour,
+                self.minute, self.second, self.microsecond,
+                self._dayofwk, self._dayofyr)
+
+ at cython.embedsignature(True)
+cdef class Datetime360Day(datetime):
+    """
+Phony datetime object which mimics the python datetime object,
+but uses the "360_day" calendar.
+    """
+    def __init__(self, *args, **kwargs):
+        kwargs['calendar']='360_day'
+        super().__init__(*args, **kwargs)
+    def __repr__(self):
+        return "{0}.{1}({2}, {3}, {4}, {5}, {6}, {7}, {8})".format('cftime',
+        self.__class__.__name__,
+        self.year,self.month,self.day,self.hour,self.minute,self.second,self.microsecond)
+    cdef _getstate(self):
+        return (self.year, self.month, self.day, self.hour,
+                self.minute, self.second, self.microsecond,
+                self._dayofwk, self._dayofyr)
+
+ at cython.embedsignature(True)
+cdef class DatetimeJulian(datetime):
+    """
+Phony datetime object which mimics the python datetime object,
+but uses the "julian" calendar.
+    """
+    def __init__(self, *args, **kwargs):
+        kwargs['calendar']='julian'
+        super().__init__(*args, **kwargs)
+    def __repr__(self):
+        return "{0}.{1}({2}, {3}, {4}, {5}, {6}, {7}, {8})".format('cftime',
+        self.__class__.__name__,
+        self.year,self.month,self.day,self.hour,self.minute,self.second,self.microsecond)
+    cdef _getstate(self):
+        return (self.year, self.month, self.day, self.hour,
+                self.minute, self.second, self.microsecond,
+                self._dayofwk, self._dayofyr)
+
+ at cython.embedsignature(True)
+cdef class DatetimeGregorian(datetime):
+    """
+Phony datetime object which mimics the python datetime object,
+but uses the mixed Julian-Gregorian ("standard", "gregorian") calendar.
+
+The last date of the Julian calendar is 1582-10-4, which is followed
+by 1582-10-15, using the Gregorian calendar.
+
+Instances using the date after 1582-10-15 can be compared to
+datetime.datetime instances and used to compute time differences
+(datetime.timedelta) by subtracting a DatetimeGregorian instance from
+a datetime.datetime instance or vice versa.
+    """
+    def __init__(self, *args, **kwargs):
+        kwargs['calendar']='gregorian'
+        super().__init__(*args, **kwargs)
+    def __repr__(self):
+        return "{0}.{1}({2}, {3}, {4}, {5}, {6}, {7}, {8})".format('cftime',
+                                     self.__class__.__name__,
+                                     self.year,self.month,self.day,self.hour,self.minute,self.second,self.microsecond)
+    cdef _getstate(self):
+        return (self.year, self.month, self.day, self.hour,
+                self.minute, self.second, self.microsecond,
+                self._dayofwk, self._dayofyr)
+
+ at cython.embedsignature(True)
+cdef class DatetimeProlepticGregorian(datetime):
+    """
+Phony datetime object which mimics the python datetime object,
+but allows for dates that don't exist in the proleptic gregorian calendar.
+
+Supports timedelta operations by overloading + and -.
+
+Has strftime, timetuple, replace, __repr__, and __str__ methods. The
+format of the string produced by __str__ is controlled by self.format
+(default %Y-%m-%d %H:%M:%S). Supports comparisons with other
+datetime instances using the same calendar; comparison with
+native python datetime instances is possible for cftime.datetime
+instances using 'gregorian' and 'proleptic_gregorian' calendars.
+
+Instance variables are year,month,day,hour,minute,second,microsecond,dayofwk,dayofyr,
+format, and calendar.
+    """
+    def __init__(self, *args, **kwargs):
+        kwargs['calendar']='proleptic_gregorian'
+        super().__init__( *args, **kwargs)
+    def __repr__(self):
+        return "{0}.{1}({2}, {3}, {4}, {5}, {6}, {7}, {8})".format('cftime',
+                                     self.__class__.__name__,
+                                     self.year,self.month,self.day,self.hour,self.minute,self.second,self.microsecond)
+    cdef _getstate(self):
+        return (self.year, self.month, self.day, self.hour,
+                self.minute, self.second, self.microsecond,
+                self._dayofwk, self._dayofyr)
+
+
+# The following function (_IntJulianDayToDate) is based on
+# algorithms described in the book
+# "Calendrical Calculations" by Dershowitz and Rheingold, 3rd edition, Cambridge University Press, 2007
+# and the C implementation provided at https://reingold.co/calendar.C
+# with modifications to handle non-real-world calendars and negative years.
+
+cdef _IntJulianDayToDate(int jday,calendar,skip_transition=False,has_year_zero=False):
+    """Compute the year,month,day,dow,doy given the integer Julian day.
+    and calendar. (dow = day of week with 0=Mon,6=Sun and doy is day of year).
+
+    Allowed calendars are 'standard', 'gregorian', 'julian',
+    'proleptic_gregorian','360_day', '365_day', '366_day', 'noleap',
+    'all_leap'.
+
+    'noleap' is a synonym for '365_day'
+    'all_leap' is a synonym for '366_day'
+    'gregorian' is a synonym for 'standard'
+
+    optional kwarg 'skip_transition':  When True, assume a 10-day
+    gap in Julian day numbers between Oct 4 and Oct 15 1582 (the transition
+    from Julian to Gregorian calendars).  Default False, ignored
+    unless calendar = 'standard'."""
+    cdef int year,month,day,dow,doy,yp1,jday_count,nextra
+    cdef int[12] dayspermonth
+    cdef int[13] cumdayspermonth
+
+    # validate inputs.
+    calendar = _check_calendar(calendar)
+
+    # compute day of week.
+    dow = (jday + 1) % 7
+    # convert to ISO 8601 (0 = Monday, 6 = Sunday), like python datetime
+    dow -= 1
+    if dow == -1: dow = 6
+
+    # handle all calendars except standard, julian, proleptic_gregorian.
+    if calendar == '360_day':
+        year   = jday//360
+        nextra = jday - year*360
+        doy    = nextra + 1 # Julday numbering starts at 0, doy starts at 1
+        month  = nextra//30 + 1
+        day    = doy - (month-1)*30
+        return year,month,day,dow,doy
+    elif calendar == '365_day':
+        year   = jday//365
+        nextra = jday - year*365
+        doy    = nextra + 1 # Julday numbering starts at 0, doy starts at 1
+        month  = 1
+        while doy > _cumdayspermonth[month]:
+            month += 1
+        day = doy - _cumdayspermonth[month-1]
+        return year,month,day,dow,doy
+    elif calendar == '366_day':
+        year   = jday//366
+        nextra = jday - year*366
+        doy    = nextra + 1 # Julday numbering starts at 0, doy starts at 1
+        month  = 1
+        while doy > _cumdayspermonth_leap[month]:
+            month += 1
+        day = doy - _cumdayspermonth_leap[month-1]
+        return year,month,day,dow,doy
+
+    # handle standard, julian, proleptic_gregorian calendars.
+    if jday < 0:
+        raise ValueError('julian day must be a positive integer')
+
+    # start with initial guess of year that is before jday=1 in both
+    # Julian and Gregorian calendars.
+    year = jday//366 - 4714
+
+    # account for 10 days in Julian/Gregorian transition.
+    if not skip_transition and calendar == 'standard' and jday > 2299160:
+        jday += 10
+
+    yp1 = year + 1
+    if yp1 == 0 and not has_year_zero:
+       yp1 = 1 # no year 0
+    # initialize jday_count to Jan 1 of next year
+    jday_count = _IntJulianDayFromDate(yp1,1,1,calendar,skip_transition=True,has_year_zero=has_year_zero)
+    # Advance years until we find the right one
+    # (stop iteration when jday_count jday >= specified jday)
+    while jday >= jday_count:
+        year += 1
+        if year == 0 and not has_year_zero:
+            year = 1
+        yp1 = year + 1
+        if yp1 == 0 and not has_year_zero:
+            yp1 = 1
+        jday_count = _IntJulianDayFromDate(yp1,1,1,calendar,skip_transition=True,has_year_zero=has_year_zero)
+    # now we know year.
+    # set days in specified month, cumulative days in computed year.
+    if _is_leap(year, calendar,has_year_zero=has_year_zero):
+        dayspermonth = _dayspermonth_leap
+        cumdayspermonth = _cumdayspermonth_leap
+    else:
+        dayspermonth = _dayspermonth
+        cumdayspermonth = _cumdayspermonth
+    # initialized month to Jan, initialize jday_count to end of Jan of
+    # calculated year.
+    month = 1
+    jday_count =\
+    _IntJulianDayFromDate(year,month,dayspermonth[month-1],calendar,skip_transition=True,has_year_zero=has_year_zero)
+    # now iterate by month until jday_count >= specified jday
+    while jday > jday_count:
+        month += 1
+        jday_count =\
+        _IntJulianDayFromDate(year,month,dayspermonth[month-1],calendar,skip_transition=True,has_year_zero=has_year_zero)
+    # back up jday_count to 1st day of computed month
+    jday_count = _IntJulianDayFromDate(year,month,1,calendar,skip_transition=True,has_year_zero=has_year_zero)
+    # now jday_count represents day 1 of computed month in computed year
+    # so computed day is just difference between jday_count and specified jday.
+    day = jday - jday_count + 1
+    # compute day in specified year.
+    doy = cumdayspermonth[month-1]+day
+    return year,month,day,dow,doy
+
+def _round_half_up(x):
+    # 'round half up' so 0.5 rounded to 1 (instead of 0 as in numpy.round)
+    return np.ceil(np.floor(2.*x)/2.)
+
+ at cython.embedsignature(True)
+def JulianDayFromDate(date, calendar='standard'):
+    """JulianDayFromDate(date, calendar='standard')
+
+    creates a Julian Day from a 'datetime-like' object.  Returns the fractional
+    Julian Day (approximately 100 microsecond accuracy).
+
+    if calendar='standard' or 'gregorian' (default), Julian day follows Julian
+    Calendar on and before 1582-10-5, Gregorian calendar after 1582-10-15.
+
+    if calendar='proleptic_gregorian', Julian Day follows gregorian calendar.
+
+    if calendar='julian', Julian Day follows julian calendar.
+    """
+
+    # check if input was scalar and change return accordingly
+    isscalar = False
+    try:
+        date[0]
+    except:
+        isscalar = True
+
+    date = np.atleast_1d(np.array(date))
+    year = np.empty(len(date), dtype=np.int32)
+    month = year.copy()
+    day = year.copy()
+    hour = year.copy()
+    minute = year.copy()
+    second = year.copy()
+    microsecond = year.copy()
+    jd = np.empty(year.shape, np.longdouble)
+    cdef long double[:] jd_view = jd
+    cdef Py_ssize_t i_max = len(date)
+    cdef Py_ssize_t i
+    for i in range(i_max):
+        d = date[i]
+        if getattr(d, 'tzinfo', None) is not None:
+            d = d.replace(tzinfo=None) - d.utcoffset()
+
+        year[i] = d.year
+        month[i] = d.month
+        day[i] = d.day
+        hour[i] = d.hour
+        minute[i] = d.minute
+        second[i] = d.second
+        microsecond[i] = d.microsecond
+        jd_view[i] = <double>_IntJulianDayFromDate(<int>year[i],<int>month[i],<int>day[i],calendar)
+
+    # at this point jd is an integer representing noon UTC on the given
+    # year,month,day.
+    # compute fractional day from hour,minute,second,microsecond
+    fracday = hour / 24.0 + minute / 1440.0 + (second + microsecond/1.e6) / 86400.0
+    jd = jd - 0.5 + fracday
+
+    if isscalar:
+        return jd[0]
+    else:
+        return jd
+
+ at cython.embedsignature(True)
+def DateFromJulianDay(JD, calendar='standard', only_use_cftime_datetimes=True,
+                      return_tuple=False):
+    """
+
+    returns a 'datetime-like' object given Julian Day. Julian Day is a
+    fractional day with approximately 100 microsecond accuracy.
+
+    if calendar='standard' or 'gregorian' (default), Julian day follows Julian
+    Calendar on and before 1582-10-5, Gregorian calendar after  1582-10-15.
+
+    if calendar='proleptic_gregorian', Julian Day follows gregorian calendar.
+
+    if calendar='julian', Julian Day follows julian calendar.
+
+    If only_use_cftime_datetimes is set to True, then cftime.datetime
+    objects are returned for all calendars.  Otherwise the datetime object is a
+    native python datetime object if the date falls in the Gregorian calendar
+    (i.e. calendar='proleptic_gregorian', or  calendar = 'standard'/'gregorian'
+    and the date is after 1582-10-15).
+    """
+
+    julian = np.atleast_1d(np.array(JD, dtype=np.longdouble))
+
+    def getdateinfo(julian):
+        # get the day (Z) and the fraction of the day (F)
+        # use 'round half up' rounding instead of numpy's even rounding
+        # so that 0.5 is rounded to 1.0, not 0 (cftime issue #49)
+        Z = np.atleast_1d(np.int32(_round_half_up(julian)))
+        F = (julian + 0.5 - Z).astype(np.longdouble)
+
+        cdef Py_ssize_t i_max = len(Z)
+        year = np.empty(i_max, dtype=np.int32)
+        month = np.empty(i_max, dtype=np.int32)
+        day = np.empty(i_max, dtype=np.int32)
+        dayofyr = np.zeros(i_max,dtype=np.int32)
+        dayofwk = np.zeros(i_max,dtype=np.int32)
+        cdef int ijd
+        cdef Py_ssize_t i
+        for i in range(i_max):
+            ijd = Z[i]
+            year[i],month[i],day[i],dayofwk[i],dayofyr[i] = _IntJulianDayToDate(ijd,calendar)
+
+        if calendar in ['standard', 'gregorian']:
+            ind_before = np.where(julian < 2299160.5)
+            ind_before = np.asarray(ind_before).any()
+        else:
+            ind_before = False
+
+        # compute hour, minute, second, microsecond, convert to int32
+        hour = np.clip((F * 24.).astype(np.int64), 0, 23)
+        F   -= hour / 24.
+        minute = np.clip((F * 1440.).astype(np.int64), 0, 59)
+        second = np.clip((F - minute / 1440.) * 86400., 0, None)
+        microsecond = (second % 1)*1.e6
+        hour = hour.astype(np.int32)
+        minute = minute.astype(np.int32)
+        second = second.astype(np.int32)
+        microsecond = microsecond.astype(np.int32)
+
+        return year,month,day,hour,minute,second,microsecond,dayofyr,dayofwk,ind_before
+
+    year,month,day,hour,minute,second,microsecond,dayofyr,dayofwk,ind_before =\
+    getdateinfo(julian)
+    # round to nearest second if within ms_eps microseconds
+    # (to avoid ugly errors in datetime formatting - alternative
+    # to adding small offset all the time as was done previously)
+    # see netcdf4-python issue #433 and cftime issue #78
+    # this is done by rounding microsends up or down, then
+    # recomputing year,month,day etc
+    # ms_eps is proportional to julian day,
+    # about 47 microseconds in 2000 for Julian base date in -4713
+    ms_eps = np.atleast_1d(np.array(np.finfo(np.float64).eps,np.longdouble))
+    ms_eps = 86400000000.*np.maximum(ms_eps*julian, ms_eps)
+    microsecond = np.where(microsecond < ms_eps, 0, microsecond)
+    indxms = microsecond > 1000000-ms_eps
+    if indxms.any():
+        julian[indxms] = julian[indxms] + 2*ms_eps[indxms]/86400000000..
+        year[indxms],month[indxms],day[indxms],hour[indxms],minute[indxms],second[indxms],microsecond2,dayofyr[indxms],dayofwk[indxms],ind_before2 =\
+        getdateinfo(julian[indxms])
+        microsecond[indxms] = 0
+
+    # check if input was scalar and change return accordingly
+    isscalar = False
+    try:
+        JD[0]
+    except:
+        isscalar = True
+
+    if calendar == 'proleptic_gregorian':
+        # datetime.datetime does not support years < 1
+        #if year < 0:
+        if only_use_cftime_datetimes:
+            datetime_type = DatetimeProlepticGregorian
+        else:
+            if (year < 0).any(): # netcdftime issue #28
+               datetime_type = DatetimeProlepticGregorian
+            else:
+               datetime_type = real_datetime
+    elif calendar in ('standard', 'gregorian'):
+        # return a 'real' datetime instance if calendar is proleptic
+        # Gregorian or Gregorian and all dates are after the
+        # Julian/Gregorian transition
+        if ind_before and not only_use_cftime_datetimes:
+            datetime_type = real_datetime
+        else:
+            datetime_type = DatetimeGregorian
+    elif calendar == "julian":
+        datetime_type = DatetimeJulian
+    elif calendar in ["noleap","365_day"]:
+        datetime_type = DatetimeNoLeap
+    elif calendar in ["all_leap","366_day"]:
+        datetime_type = DatetimeAllLeap
+    elif calendar == "360_day":
+        datetime_type = Datetime360Day
+    else:
+        raise ValueError("unsupported calendar: {0}".format(calendar))
+
+    if not isscalar:
+        if return_tuple:
+            return np.array([args for args in
+                            zip(year, month, day, hour, minute, second,
+                                microsecond,dayofwk,dayofyr)])
+        else:
+            return np.array([datetime_type(*args)
+                             for args in
+                             zip(year, month, day, hour, minute, second,
+                                 microsecond)])
+
+    else:
+        if return_tuple:
+            return (year[0], month[0], day[0], hour[0],
+                    minute[0], second[0], microsecond[0],
+                    dayofwk[0], dayofyr[0])
+        else:
+            return datetime_type(year[0], month[0], day[0], hour[0],
+                                 minute[0], second[0], microsecond[0])
+
+class utime:
+
+    """
+Performs conversions of netCDF time coordinate
+data to/from datetime objects.
+
+To initialize: `t = utime(unit_string,calendar='standard'`
+
+where
+
+`unit_string` is a string of the form
+`time-units since <time-origin>` defining the time units.
+
+Valid time-units are days, hours, minutes and seconds (the singular forms
+are also accepted). An example unit_string would be `hours
+since 0001-01-01 00:00:00`. months is allowed as a time unit
+*only* for the 360_day calendar.
+
+The calendar keyword describes the calendar used in the time calculations.
+All the values currently defined in the U{CF metadata convention
+<http://cf-pcmdi.llnl.gov/documents/cf-conventions/1.1/cf-conventions.html#time-coordinate>}
+are accepted. The default is 'standard', which corresponds to the mixed
+Gregorian/Julian calendar used by the udunits library. Valid calendars
+are:
+
+'gregorian' or 'standard' (default):
+
+Mixed Gregorian/Julian calendar as defined by udunits.
+
+'proleptic_gregorian':
+
+A Gregorian calendar extended to dates before 1582-10-15. That is, a year
+is a leap year if either (i) it is divisible by 4 but not by 100 or (ii)
+it is divisible by 400.
+
+'noleap' or '365_day':
+
+Gregorian calendar without leap years, i.e., all years are 365 days long..
+all_leap or 366_day Gregorian calendar with every year being a leap year,
+i.e., all years are 366 days long.
+
+'360_day':
+
+All years are 360 days divided into 30 day months.
+
+'julian':
+
+Proleptic Julian calendar, extended to dates after 1582-10-5. A year is a
+leap year if it is divisible by 4.
+
+The num2date and date2num class methods can used to convert datetime
+instances to/from the specified time units using the specified calendar.
+
+Example usage:
+
+>>> from cftime import utime
+>>> from datetime import  datetime
+>>> cdftime = utime('hours since 0001-01-01 00:00:00')
+>>> date = datetime.now()
+>>> print date
+2016-10-05 08:46:27.245015
+>>>
+>>> t = cdftime.date2num(date)
+>>> print t
+17669840.7742
+>>>
+>>> date = cdftime.num2date(t)
+>>> print date
+2016-10-05 08:46:27.244996
+>>>
+
+The resolution of the transformation operation is approximately a microsecond.
+
+Warning:  Dates between 1582-10-5 and 1582-10-15 do not exist in the
+'standard' or 'gregorian' calendars.  An exception will be raised if you pass
+a 'datetime-like' object in that range to the date2num class method.
+
+Words of Wisdom from the British MetOffice concerning reference dates:
+
+"udunits implements the mixed Gregorian/Julian calendar system, as
+followed in England, in which dates prior to 1582-10-15 are assumed to use
+the Julian calendar. Other software cannot be relied upon to handle the
+change of calendar in the same way, so for robustness it is recommended
+that the reference date be later than 1582. If earlier dates must be used,
+it should be noted that udunits treats 0 AD as identical to 1 AD."
+
+ at ivar origin: datetime instance defining the origin of the netCDF time variable.
+ at ivar calendar:  the calendar used (as specified by the `calendar` keyword).
+ at ivar unit_string:  a string defining the the netCDF time variable.
+ at ivar units:  the units part of `unit_string` (i.e. 'days', 'hours', 'seconds').
+    """
+
+    def __init__(self, unit_string, calendar='standard',
+                 only_use_cftime_datetimes=True,only_use_python_datetimes=False):
+        """
+ at param unit_string: a string of the form
+`time-units since <time-origin>` defining the time units.
+
+Valid time-units are days, hours, minutes and seconds (the singular forms
+are also accepted). An example unit_string would be `hours
+since 0001-01-01 00:00:00`. months is allowed as a time unit
+*only* for the 360_day calendar.
+
+ at keyword calendar: describes the calendar used in the time calculations.
+All the values currently defined in the U{CF metadata convention
+<http://cf-pcmdi.llnl.gov/documents/cf-conventions/1.1/cf-conventions.html#time-coordinate>}
+are accepted. The default is `standard`, which corresponds to the mixed
+Gregorian/Julian calendar used by the udunits library. Valid calendars
+are:
+ - `gregorian` or `standard` (default):
+ Mixed Gregorian/Julian calendar as defined by udunits.
+ - `proleptic_gregorian`:
+ A Gregorian calendar extended to dates before 1582-10-15. That is, a year
+ is a leap year if either (i) it is divisible by 4 but not by 100 or (ii)
+ it is divisible by 400.
+ - `noleap` or `365_day`:
+ Gregorian calendar without leap years, i.e., all years are 365 days long.
+ - `all_leap` or `366_day`:
+ Gregorian calendar with every year being a leap year, i.e.,
+ all years are 366 days long.
+ -`360_day`:
+ All years are 360 days divided into 30 day months.
+ -`julian`:
+ Proleptic Julian calendar, extended to dates after 1582-10-5. A year is a
+ leap year if it is divisible by 4.
+
+ at keyword only_use_cftime_datetimes: if False, datetime.datetime
+objects are returned from num2date where possible; if True dates which subclass
+cftime.datetime are returned for all calendars. Default True.
+
+ at keyword only_use_python_datetimes: always return python datetime.datetime
+objects and raise an error if this is not possible. Ignored unless
+**only_use_cftime_datetimes=False**. Default **False**.
+
+ at returns: A class instance which may be used for converting times from netCDF
+units to datetime objects.
+        """
+        calendar = calendar.lower()
+        if calendar in _calendars:
+            self.calendar = calendar
+        else:
+            raise ValueError(
+                "calendar must be one of %s, got '%s'" % (str(_calendars), calendar))
+        self.origin = _dateparse(unit_string,calendar=calendar)
+        units, isostring = _datesplit(unit_string)
+        self.units = units
+        self.unit_string = unit_string
+        self.only_use_cftime_datetimes = only_use_cftime_datetimes
+        self.only_use_python_datetimes = only_use_python_datetimes
+
+    def date2num(self, date):
+        """
+        Returns `time_value` in units described by `unit_string`, using
+        the specified `calendar`, given a 'datetime-like' object.
+
+        The datetime object must represent UTC with no time-zone offset.
+        If there is a time-zone offset implied by L{unit_string}, it will
+        be applied to the returned numeric values.
+
+        Resolution is approximately a microsecond.
+
+        If calendar = 'standard' or 'gregorian' (indicating
+        that the mixed Julian/Gregorian calendar is to be used), an
+        exception will be raised if the 'datetime-like' object describes
+        a date between 1582-10-5 and 1582-10-15.
+
+        Works for scalars, sequences and numpy arrays.
+        Returns a scalar if input is a scalar, else returns a numpy array.
+        """
+        return date2num(date,self.unit_string,calendar=self.calendar)
+
+    def num2date(self, time_value):
+        """
+        Return a 'datetime-like' object given a `time_value` in units
+        described by `unit_string`, using `calendar`.
+
+        dates are in UTC with no offset, even if L{unit_string} contains
+        a time zone offset from UTC.
+
+        Resolution is approximately a microsecond.
+
+        Works for scalars, sequences and numpy arrays.
+        Returns a scalar if input is a scalar, else returns a numpy array.
+        """
+        return num2date(time_value,self.unit_string,calendar=self.calendar,only_use_cftime_datetimes=self.only_use_cftime_datetimes,only_use_python_datetimes=self.only_use_python_datetimes)


=====================================
test/test_cftime.py
=====================================
@@ -290,10 +290,13 @@ class cftimeTestCase(unittest.TestCase):
         date = self.cdftime_jul.num2date(t)
         self.assertTrue(str(d) == str(date))
         # test julian day from date, date from julian day
-        d = datetime(1858, 11, 17)
-        mjd = JulianDayFromDate(d)
-        assert_almost_equal(mjd, 2400000.5)
-        date = DateFromJulianDay(mjd)
+        d = cftime.datetime(1858, 11, 17, calendar='standard')
+        # toordinal should produce same result as JulidaDayFromDate
+        mjd1 = d.toordinal(fractional=True)
+        mjd2 = JulianDayFromDate(d)
+        assert_almost_equal(mjd1, 2400000.5)
+        assert_almost_equal(mjd1,mjd2)
+        date = DateFromJulianDay(mjd1)
         self.assertTrue(str(date) == str(d))
         # test iso 8601 units string
         d = datetime(1970, 1, 1, 1)
@@ -737,7 +740,8 @@ class cftimeTestCase(unittest.TestCase):
         test = dates == np.ma.masked_array([datetime(1848, 1, 17, 6, 0, 0, 40), None],mask=[0,1])
         assert(test.all())
         dates = num2date(times, units=units, calendar='standard')
-        assert(str(dates)=="[cftime.DatetimeGregorian(1848, 1, 17, 6, 0, 0, 40) --]")
+        assert(str(dates)==\
+        "[cftime.datetime(1848, 1, 17, 6, 0, 0, 40, calendar='gregorian') --]")
 #  check that time range of 200,000 + years can be represented accurately
         calendar='standard'
         _MAX_INT64 = np.iinfo("int64").max
@@ -1888,5 +1892,46 @@ def test_num2date_integer_upcast_required():
     np.testing.assert_equal(result, expected)
 
 
+ at pytest.mark.parametrize(
+    "encoding_units", 
+    ["microseconds", "milliseconds", "seconds", "minutes", "hours", "days"]
+)
+ at pytest.mark.parametrize(
+    "freq",
+    [
+        timedelta(microseconds=1),
+        timedelta(microseconds=1000), 
+        timedelta(seconds=1), 
+        timedelta(minutes=1), 
+        timedelta(hours=1), 
+        timedelta(days=1)
+    ], 
+    ids=lambda x: f"{x!r}"
+)
+def test_date2num_num2date_roundtrip(encoding_units, freq, calendar):
+    date_type = _EXPECTED_DATE_TYPES[calendar]
+    lengthy_timedelta = timedelta(days=291000 * 360)
+    times = np.array(
+        [
+            date_type(1, 1, 1), 
+            date_type(1, 1, 1) + lengthy_timedelta, 
+            date_type(1, 1, 1) + lengthy_timedelta + freq
+        ]
+    )
+    units = f"{encoding_units} since 0001-01-01"
+    encoded = date2num(times, units=units, calendar=calendar)
+    decoded = num2date(encoded, units=units, calendar=calendar)
+    encoding_units_as_timedelta = timedelta(microseconds=UNIT_CONVERSION_FACTORS[encoding_units])
+
+    if freq >= encoding_units_as_timedelta:
+        assert encoded.dtype == np.int64
+        np.testing.assert_equal(decoded, times)
+    else:
+        assert encoded.dtype == np.float64
+        tolerance = timedelta(microseconds=2000)
+        meets_tolerance = np.abs(decoded - times) <= tolerance
+        assert np.all(meets_tolerance)
+
+
 if __name__ == '__main__':
     unittest.main()



View it on GitLab: https://salsa.debian.org/debian-gis-team/cftime/-/compare/3ce983daa3fc91e85092346cbb9e8f4d0a1b0d68...3a1a9109409c526266072a8715576f8dcaf190eb

-- 
View it on GitLab: https://salsa.debian.org/debian-gis-team/cftime/-/compare/3ce983daa3fc91e85092346cbb9e8f4d0a1b0d68...3a1a9109409c526266072a8715576f8dcaf190eb
You're receiving this email because of your account on salsa.debian.org.


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://alioth-lists.debian.net/pipermail/pkg-grass-devel/attachments/20210201/001ef63d/attachment-0001.html>


More information about the Pkg-grass-devel mailing list