[Git][debian-gis-team/cftime][master] 5 commits: New upstream version 1.0.2

Bas Couwenberg gitlab at salsa.debian.org
Sat Oct 27 09:24:51 BST 2018


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


Commits:
e2ea7178 by Bas Couwenberg at 2018-10-27T07:54:29Z
New upstream version 1.0.2
- - - - -
226433fa by Bas Couwenberg at 2018-10-27T07:54:30Z
Merge tag 'upstream/1.0.2'

Upstream version 1.0.2

- - - - -
0e82d947 by Bas Couwenberg at 2018-10-27T07:54:44Z
New upstream release.

- - - - -
ad8651a1 by Bas Couwenberg at 2018-10-27T08:03:03Z
Update copyright file to include GPL-3+ for calcalcs code.

- - - - -
02d0fba7 by Bas Couwenberg at 2018-10-27T08:04:30Z
Set distribution to unstable.

- - - - -


8 changed files:

- COPYING
- README.md
- cftime/__init__.py
- cftime/_cftime.pyx
- debian/changelog
- debian/copyright
- + test/benchmark.py
- test/test_cftime.py


Changes:

=====================================
COPYING
=====================================
@@ -37,3 +37,196 @@ 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


=====================================
README.md
=====================================
@@ -6,6 +6,10 @@ Time-handling functionality from netcdf4-python
 [![PyPI package](https://badge.fury.io/py/cftime.svg)](http://python.org/pypi/cftime)
 
 ## News
+10/27/2018:  version 1.0.2 released. Improved accuracy (from approximately 1000 microseconds to 10 microseconds on x86
+platforms). Refactored calendar calculations now allow for negative reference years. num2date function now more than an
+order of magnitude faster. `months since` units now allowed, but only for `360_day` calendar.
+
 08/15/2018:  version 1.0.1 released.
 
 11/8/2016: `cftime` was split out of the [netcdf4-python](https://github.com/Unidata/netcdf4-python) package.


=====================================
cftime/__init__.py
=====================================
@@ -1,6 +1,6 @@
 from ._cftime import utime, JulianDayFromDate, DateFromJulianDay
 from ._cftime import _parse_date, date2index, time2index
-from ._cftime import datetime
+from ._cftime import datetime, real_datetime
 from ._cftime import DatetimeNoLeap, DatetimeAllLeap, Datetime360Day, DatetimeJulian, \
                          DatetimeGregorian, DatetimeProlepticGregorian
 from ._cftime import microsec_units, millisec_units, \


=====================================
cftime/_cftime.pyx
=====================================
@@ -5,11 +5,10 @@ Performs conversions of netCDF time coordinate data to/from datetime objects.
 from cpython.object cimport PyObject_RichCompare
 import cython
 import numpy as np
-import math
-import numpy
 import re
+import sys
 import time
-from datetime import datetime as real_datetime
+from datetime import datetime as datetime_python
 from datetime import timedelta, MINYEAR
 import time                     # strftime
 try:
@@ -23,11 +22,23 @@ sec_units =      ['second', 'seconds', 'sec', 'secs', 's']
 min_units =      ['minute', 'minutes', 'min', 'mins']
 hr_units =       ['hour', 'hours', 'hr', 'hrs', 'h']
 day_units =      ['day', 'days', 'd']
+month_units =    ['month', 'months'] # only allowed for 360_day calendar
 _units = microsec_units+millisec_units+sec_units+min_units+hr_units+day_units
+# supported calendars. Includes synonyms ('standard'=='gregorian',
+# '366_day'=='all_leap','365_day'=='noleap')
+# see http://cfconventions.org/cf-conventions/cf-conventions.html#calendar 
+# 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]
 
-__version__ = '1.0.1'
+__version__ = '1.0.2'
 
 # 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.
@@ -41,6 +52,15 @@ ISO8601_REGEX = re.compile(r"(?P<year>[+-]?[0-9]{1,4})(-(?P<month>[0-9]{1,2})(-(
 TIMEZONE_REGEX = re.compile(
     "(?P<prefix>[+-])(?P<hours>[0-9]{2})(?:(?::(?P<minutes1>[0-9]{2}))|(?P<minutes2>[0-9]{2}))?")
 
+class real_datetime(datetime_python):
+    """add dayofwk and dayofyr attributes to python datetime instance"""
+    @property
+    def dayofwk(self):
+        # 0=Monday, 6=Sunday
+        return self.weekday()
+    @property
+    def dayofyr(self):
+        return self.timetuple().tm_yday
 
 # start of the gregorian calendar
 gregorian = real_datetime(1582,10,15)
@@ -81,13 +101,19 @@ def _dateparse(timestr):
             raise ValueError('cannot use utc_offset for reference years <= 0')
     return basedate
 
+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.)
 
-cdef _parse_date_and_units(timestr):
+cdef _parse_date_and_units(timestr,calendar='standard'):
     """parse a string of the form time-units since yyyy-mm-dd hh:mm:ss
     return a tuple (units,utc_offset, datetimeinstance)"""
     (units, isostring) = _datesplit(timestr)
-    if units not in _units:
-        raise ValueError(
+    if not ((units in month_units and calendar=='360_day') or units in _units):
+        if units in month_units and calendar != '360_day':
+            raise ValueError("'months since' units only allowed for '360_day' calendar")
+        else:
+            raise ValueError(
             "units must be one of 'seconds', 'minutes', 'hours' or 'days' (or singular version of these), got '%s'" % units)
     # parse the date string.
     year, month, day, hour, minute, second, utc_offset = _parse_date(
@@ -111,7 +137,7 @@ def date2num(dates,units,calendar='standard'):
     **`units`**: a string of the form `<time units> since <reference time>`
     describing the time units. `<time units>` can be days, hours, minutes,
     seconds, milliseconds or microseconds. `<reference time>` is the time
-    origin.
+    origin. `months_since` is allowed *only* for the `360_day` calendar.
 
     **`calendar`**: describes the calendar used in the time calculations.
     All the values currently defined in the
@@ -121,7 +147,7 @@ def date2num(dates,units,calendar='standard'):
     Default is `'standard'`, which is a mixed Julian/Gregorian calendar.
 
     returns a numeric time value, or an array of numeric time values
-    with approximately millisecond accuracy.
+    with approximately 10 microsecond accuracy.
         """
         calendar = calendar.lower()
         basedate = _dateparse(units)
@@ -131,9 +157,6 @@ def date2num(dates,units,calendar='standard'):
             if basedate.year == 0:
                 msg='zero not allowed as a reference year, does not exist in Julian or Gregorian calendars'
                 raise ValueError(msg)
-            elif basedate.year < 0:
-                msg='negative reference year in time units, must be >= 1'
-                raise ValueError(msg)
 
         if (calendar == 'proleptic_gregorian' and basedate.year >= MINYEAR) or \
            (calendar in ['gregorian','standard'] and basedate > gregorian):
@@ -144,12 +167,12 @@ def date2num(dates,units,calendar='standard'):
             except:
                 isscalar = True
             if isscalar:
-                dates = numpy.array([dates])
+                dates = np.array([dates])
             else:
-                dates = numpy.array(dates)
+                dates = np.array(dates)
                 shape = dates.shape
             ismasked = False
-            if numpy.ma.isMA(dates) and numpy.ma.is_masked(dates):
+            if np.ma.isMA(dates) and np.ma.is_masked(dates):
                 mask = dates.mask
                 ismasked = True
             times = []
@@ -177,7 +200,7 @@ def date2num(dates,units,calendar='standard'):
             if isscalar:
                 return times[0]
             else:
-                return numpy.reshape(numpy.array(times), shape)
+                return np.reshape(np.array(times), shape)
         else: # use cftime module for other calendars
             cdftime = utime(units,calendar=calendar)
             return cdftime.date2num(dates)
@@ -197,7 +220,7 @@ def num2date(times,units,calendar='standard',only_use_cftime_datetimes=False):
     **`units`**: a string of the form `<time units> since <reference time>`
     describing the time units. `<time units>` can be days, hours, minutes,
     seconds, milliseconds or microseconds. `<reference time>` is the time
-    origin.
+    origin. `months_since` is allowed *only* for the `360_day` calendar.
 
     **`calendar`**: describes the calendar used in the time calculations.
     All the values currently defined in the
@@ -211,7 +234,7 @@ def num2date(times,units,calendar='standard',only_use_cftime_datetimes=False):
     subclass cftime.datetime are returned for all calendars.
 
     returns a datetime instance, or an array of datetime instances with
-    approximately millisecond accuracy.
+    approximately 10 microsecond accuracy.
 
     ***Note***: The datetime instances returned are 'real' python datetime
     objects if `calendar='proleptic_gregorian'`, or
@@ -231,11 +254,8 @@ def num2date(times,units,calendar='standard',only_use_cftime_datetimes=False):
         if basedate.year == 0:
             msg='zero not allowed as a reference year, does not exist in Julian or Gregorian calendars'
             raise ValueError(msg)
-        elif basedate.year < 0:
-            msg='negative reference year in time units, must be >= 1'
-            raise ValueError(msg)
 
-    postimes =  (numpy.asarray(times) > 0).all() # netcdf4-python issue #659
+    postimes =  (np.asarray(times) > 0).all() # netcdf4-python issue #659
     if only_use_cftime_datetimes:
         cdftime = utime(units, calendar=calendar,
                         only_use_cftime_datetimes=only_use_cftime_datetimes)
@@ -249,12 +269,12 @@ def num2date(times,units,calendar='standard',only_use_cftime_datetimes=False):
         except:
             isscalar = True
         if isscalar:
-            times = numpy.array([times],dtype='d')
+            times = np.array([times],dtype='d')
         else:
-            times = numpy.array(times, dtype='d')
+            times = np.array(times, dtype='d')
             shape = times.shape
         ismasked = False
-        if numpy.ma.isMA(times) and numpy.ma.is_masked(times):
+        if np.ma.isMA(times) and np.ma.is_masked(times):
             mask = times.mask
             ismasked = True
         dates = []
@@ -281,7 +301,7 @@ def num2date(times,units,calendar='standard',only_use_cftime_datetimes=False):
                 days = tsecs // 86400.
                 msecsd = tsecs*1.e6 - days*86400.*1.e6
                 secs = msecsd // 1.e6
-                msecs = numpy.round(msecsd - secs*1.e6)
+                msecs = np.round(msecsd - secs*1.e6)
                 td = timedelta(days=days,seconds=secs,microseconds=msecs)
                 # add time delta to base date.
                 date = basedate + td
@@ -289,7 +309,7 @@ def num2date(times,units,calendar='standard',only_use_cftime_datetimes=False):
         if isscalar:
             return dates[0]
         else:
-            return numpy.reshape(numpy.array(dates), shape)
+            return np.reshape(np.array(dates), shape)
     else: # use cftime for other calendars
         cdftime = utime(units,calendar=calendar)
         return cdftime.num2date(times)
@@ -338,9 +358,6 @@ def date2index(dates, nctime, calendar=None, select='exact'):
         if basedate.year == 0:
             msg='zero not allowed as a reference year, does not exist in Julian or Gregorian calendars'
             raise ValueError(msg)
-        elif basedate.year < 0:
-            msg='negative reference year in time units, must be >= 1'
-            raise ValueError(msg)
 
     if (calendar == 'proleptic_gregorian' and basedate.year >= MINYEAR) or \
        (calendar in ['gregorian','standard'] and basedate > gregorian):
@@ -355,7 +372,7 @@ def JulianDayFromDate(date, calendar='standard'):
     """JulianDayFromDate(date, calendar='standard')
 
     creates a Julian Day from a 'datetime-like' object.  Returns the fractional
-    Julian Day (approximately millisecond accuracy).
+    Julian Day (approximately 10 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.
@@ -363,16 +380,8 @@ def JulianDayFromDate(date, calendar='standard'):
     if calendar='proleptic_gregorian', Julian Day follows gregorian calendar.
 
     if calendar='julian', Julian Day follows julian calendar.
-
-    Algorithm:
-
-    Meeus, Jean (1998) Astronomical Algorithms (2nd Edition). Willmann-Bell,
-    Virginia. p. 63
-
     """
 
-    # based on redate.py by David Finlayson.
-
     # check if input was scalar and change return accordingly
     isscalar = False
     try:
@@ -388,7 +397,12 @@ def JulianDayFromDate(date, calendar='standard'):
     minute = year.copy()
     second = year.copy()
     microsecond = year.copy()
-    for i, d in enumerate(date):
+    jd = np.empty(year.shape, np.float128)
+    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]
         year[i] = d.year
         month[i] = d.month
         day[i] = d.day
@@ -396,161 +410,33 @@ def JulianDayFromDate(date, calendar='standard'):
         minute[i] = d.minute
         second[i] = d.second
         microsecond[i] = d.microsecond
-    # convert years in BC era to astronomical years (so that 1 BC is year zero)
-    # (fixes netcdf4-python issue #596)
-    year[year < 0] = year[year < 0] + 1
-    # Convert time to fractions of a day
-    day = day + hour / 24.0 + minute / 1440.0 + (second + microsecond/1.e6) / 86400.0
-
-    # Start Meeus algorithm (variables are in his notation)
-    month_lt_3 = month < 3
-    month[month_lt_3] = month[month_lt_3] + 12
-    year[month_lt_3] = year[month_lt_3] - 1
-
-    # MC - assure array
-    # A = np.int64(year / 100)
-    A = (year / 100).astype(np.int64)
-
-    # MC
-    # jd = int(365.25 * (year + 4716)) + int(30.6001 * (month + 1)) + \
-    #      day - 1524.5
-    jd = 365. * year + np.int32(0.25 * year + 2000.) + np.int32(30.6001 * (month + 1)) + \
-        day + 1718994.5
-
-    # optionally adjust the jd for the switch from
-    # the Julian to Gregorian Calendar
-    # here assumed to have occurred the day after 1582 October 4
-    if calendar in ['standard', 'gregorian']:
-        # MC - do not have to be contiguous dates
-        # if np.min(jd) >= 2299170.5:
-        #     # 1582 October 15 (Gregorian Calendar)
-        #     B = 2 - A + np.int32(A / 4)
-        # elif np.max(jd) < 2299160.5:
-        #     # 1582 October 5 (Julian Calendar)
-        #     B = np.zeros(len(jd))
-        # else:
-        #     print(date, calendar, jd)
-        #     raise ValueError(
-        #         'impossible date (falls in gap between end of Julian calendar and beginning of Gregorian calendar')
-        if np.any((jd >= 2299160.5) & (jd < 2299170.5)): # missing days in Gregorian calendar
-            raise ValueError(
-                'impossible date (falls in gap between end of Julian calendar and beginning of Gregorian calendar')
-        B = np.zeros(len(jd))             # 1582 October 5 (Julian Calendar)
-        ii = np.where(jd >= 2299170.5)[0] # 1582 October 15 (Gregorian Calendar)
-        if ii.size>0:
-            B[ii] = 2 - A[ii] + np.int32(A[ii] / 4)
-    elif calendar == 'proleptic_gregorian':
-        B = 2 - A + np.int32(A / 4)
-    elif calendar == 'julian':
-        B = np.zeros(len(jd))
-    else:
-        raise ValueError(
-            'unknown calendar, must be one of julian,standard,gregorian,proleptic_gregorian, got %s' % calendar)
+        jd_view[i] = <double>_IntJulianDayFromDate(<int>year[i],<int>month[i],<int>day[i],calendar)
 
-    # adjust for Julian calendar if necessary
-    jd = jd + B
+    # 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
 
     # Add a small offset (proportional to Julian date) for correct re-conversion.
     # This is about 45 microseconds in 2000 for Julian date starting -4712.
     # (pull request #433).
-    eps = np.finfo(float).eps
-    eps = np.maximum(eps*jd, eps)
-    jd += eps
+    if calendar not in ['all_leap','no_leap','360_day','365_day','366_day']:
+        eps = np.array(np.finfo(np.float64).eps,np.float128)
+        eps = np.maximum(eps*jd, eps)
+        jd += eps
 
     if isscalar:
         return jd[0]
     else:
         return jd
 
-
-cdef _NoLeapDayFromDate(date):
-    """
-
-creates a Julian Day for a calendar with no leap years from a datetime
-instance.  Returns the fractional Julian Day (approximately millisecond accuracy).
-
-    """
-
-    year = date.year
-    month = date.month
-    day = date.day
-    hour = date.hour
-    minute = date.minute
-    second = date.second
-    microsecond = date.microsecond
-    # Convert time to fractions of a day
-    day = day + hour / 24.0 + minute / 1440.0 + (second + microsecond/1.e6) / 86400.0
-
-    # Start Meeus algorithm (variables are in his notation)
-    if (month < 3):
-        month = month + 12
-        year = year - 1
-
-    jd = int(365. * (year + 4716)) + int(30.6001 * (month + 1)) + \
-        day - 1524.5
-
-    return jd
-
-
-cdef _AllLeapFromDate(date):
-    """
-
-creates a Julian Day for a calendar where all years have 366 days from
-a 'datetime-like' object.
-Returns the fractional Julian Day (approximately millisecond accuracy).
-
-    """
-
-    year = date.year
-    month = date.month
-    day = date.day
-    hour = date.hour
-    minute = date.minute
-    second = date.second
-    microsecond = date.microsecond
-    # Convert time to fractions of a day
-    day = day + hour / 24.0 + minute / 1440.0 + (second + microsecond/1.e6) / 86400.0
-
-    # Start Meeus algorithm (variables are in his notation)
-    if (month < 3):
-        month = month + 12
-        year = year - 1
-
-    jd = int(366. * (year + 4716)) + int(30.6001 * (month + 1)) + \
-        day - 1524.5
-
-    return jd
-
-
-cdef _360DayFromDate(date):
-    """
-
-creates a Julian Day for a calendar where all months have 30 days from
-a 'datetime-like' object.
-Returns the fractional Julian Day (approximately millisecond accuracy).
-
-    """
-
-    year = date.year
-    month = date.month
-    day = date.day
-    hour = date.hour
-    minute = date.minute
-    second = date.second
-    microsecond = date.microsecond
-    # Convert time to fractions of a day
-    day = day + hour / 24.0 + minute / 1440.0 + (second + microsecond/1.e6) / 86400.0
-
-    jd = int(360. * (year + 4716)) + int(30. * (month - 1)) + day
-
-    return jd
-
-
-def DateFromJulianDay(JD, calendar='standard', only_use_cftime_datetimes=False):
+def DateFromJulianDay(JD, calendar='standard', only_use_cftime_datetimes=False,
+                      return_tuple=False):
     """
 
     returns a 'datetime-like' object given Julian Day. Julian Day is a
-    fractional day with approximately millisecond accuracy.
+    fractional day with approximately 10 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.
@@ -565,95 +451,33 @@ def DateFromJulianDay(JD, calendar='standard', only_use_cftime_datetimes=False):
     (i.e. calendar='proleptic_gregorian', or  calendar = 'standard'/'gregorian'
     and the date is after 1582-10-15).  In all other cases a 'phony' datetime
     objects are used, which are actually instances of cftime.datetime.
-
-    Algorithm:
-
-    Meeus, Jean (1998) Astronomical Algorithms (2nd Edition). Willmann-Bell,
-    Virginia. p. 63
     """
 
-    # based on redate.py by David Finlayson.
+    julian = np.array(JD, dtype=np.float128)
 
-    julian = np.array(JD, dtype=float)
-
-    if np.min(julian) < 0:
-        raise ValueError('Julian Day must be positive')
-
-    dayofwk = np.atleast_1d(np.int32(np.fmod(np.int32(julian + 1.5), 7)))
     # get the day (Z) and the fraction of the day (F)
-    # add 0.000005 which is 452 ms in case of jd being after
-    # second 23:59:59 of a day we want to round to the next day see issue #75
-    Z = np.atleast_1d(np.int32(np.round(julian)))
-    F = np.atleast_1d(julian + 0.5 - Z).astype(np.float64)
+    # 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 = np.atleast_1d(julian + 0.5 - Z).astype(np.float128)
+
+    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']:
-        # MC
-        # alpha = int((Z - 1867216.25)/36524.25)
-        # A = Z + 1 + alpha - int(alpha/4)
-        alpha = np.int32(((Z - 1867216.) - 0.25) / 36524.25)
-        A = Z + 1 + alpha - np.int32(0.25 * alpha)
-        # check if dates before oct 5th 1582 are in the array
         ind_before = np.where(julian < 2299160.5)[0]
-        if len(ind_before) > 0:
-            A[ind_before] = Z[ind_before]
-
-    elif calendar == 'proleptic_gregorian':
-        # MC
-        # alpha = int((Z - 1867216.25)/36524.25)
-        # A = Z + 1 + alpha - int(alpha/4)
-        alpha = np.int32(((Z - 1867216.) - 0.25) / 36524.25)
-        A = Z + 1 + alpha - np.int32(0.25 * alpha)
-    elif calendar == 'julian':
-        A = Z
-    else:
-        raise ValueError(
-            'unknown calendar, must be one of julian,standard,gregorian,proleptic_gregorian, got %s' % calendar)
-
-    B = A + 1524
-    # MC
-    # C = int((B - 122.1)/365.25)
-    # D = int(365.25 * C)
-    C = np.atleast_1d(np.int32(6680. + ((B - 2439870.) - 122.1) / 365.25))
-    D = np.atleast_1d(np.int32(365 * C + np.int32(0.25 * C)))
-    E = np.atleast_1d(np.int32((B - D) / 30.6001))
-
-    # Convert to date
-    day = np.clip(B - D - np.int64(30.6001 * E) + F, 1, None)
-    nday = B - D - 123
-    dayofyr = nday - 305
-    ind_nday_before = np.where(nday <= 305)[0]
-    if len(ind_nday_before) > 0:
-        dayofyr[ind_nday_before] = nday[ind_nday_before] + 60
-    # MC
-    # if E < 14:
-    #     month = E - 1
-    # else:
-    #     month = E - 13
-
-    # if month > 2:
-    #     year = C - 4716
-    # else:
-    #     year = C - 4715
-    month = E - 1
-    month[month > 12] = month[month > 12] - 12
-    year = C - 4715
-    year[month > 2] = year[month > 2] - 1
-    year[year <= 0] = year[year <= 0] - 1
-
-    # a leap year?
-    leap = np.zeros(len(year),dtype=dayofyr.dtype)
-    leap[year % 4 == 0] = 1
-    if calendar == 'proleptic_gregorian':
-        leap[(year % 100 == 0) & (year % 400 != 0)] = 0
-    elif calendar in ['standard', 'gregorian']:
-        leap[(year % 100 == 0) & (year % 400 != 0) & (julian < 2299160.5)] = 0
-
-    inc_idx = np.where((leap == 1) & (month > 2))[0]
-    dayofyr[inc_idx] = dayofyr[inc_idx] + leap[inc_idx]
 
     # Subtract the offset from JulianDayFromDate from the microseconds (pull
     # request #433).
-    eps = np.finfo(float).eps
-    eps = np.maximum(eps*julian, eps)
     hour = np.clip((F * 24.).astype(np.int64), 0, 23)
     F   -= hour / 24.
     minute = np.clip((F * 1440.).astype(np.int64), 0, 59)
@@ -661,12 +485,12 @@ def DateFromJulianDay(JD, calendar='standard', only_use_cftime_datetimes=False):
     second = np.clip((F - minute / 1440.) * 86400., 0, None)
     microsecond = (second % 1)*1.e6
     # remove the offset from the microsecond calculation.
-    microsecond = np.clip(microsecond - eps*86400.*1e6, 0, 999999)
+    if calendar not in ['all_leap','no_leap','360_day','365_day','366_day']:
+        eps = np.array(np.finfo(np.float64).eps,np.float128)
+        eps = np.maximum(eps*julian, eps)
+        microsecond = np.clip(microsecond - eps*86400.*1e6, 0, 999999)
 
-    # convert year, month, day, hour, minute, second to int32
-    year = year.astype(np.int32)
-    month = month.astype(np.int32)
-    day = day.astype(np.int32)
+    # convert hour, minute, second to int32
     hour = hour.astype(np.int32)
     minute = minute.astype(np.int32)
     second = second.astype(np.int32)
@@ -679,191 +503,69 @@ def DateFromJulianDay(JD, calendar='standard', only_use_cftime_datetimes=False):
     except:
         isscalar = True
 
-    if calendar in 'proleptic_gregorian':
+    is_real_dateime = False
+    if calendar == 'proleptic_gregorian':
         # datetime.datetime does not support years < 1
         #if year < 0:
         if only_use_cftime_datetimes:
-           if calendar == 'gregorian':
-              datetime_type = DatetimeGregorian
-           else:
-              datetime_type = DatetimeProlepticGregorian
+            datetime_type = DatetimeProlepticGregorian
         else:
             if (year < 0).any(): # netcdftime issue #28
                datetime_type = DatetimeProlepticGregorian
             else:
+               is_real_datetime = True
                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 len(ind_before) == 0 and not only_use_cftime_datetimes:
+            is_real_datetime = True
             datetime_type = real_datetime
         else:
+            is_real_datetime = False
             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:
-        return np.array([datetime_type(*args)
-                         for args in
-                         zip(year, month, day, hour, minute, second,
-                             microsecond)])
-
-    else:
-        return datetime_type(year[0], month[0], day[0], hour[0],
-                             minute[0], second[0], microsecond[0])
-
-
-cdef _DateFromNoLeapDay(JD):
-    """
-
-returns a 'datetime-like' object given Julian Day for a calendar with no leap
-days. Julian Day is a fractional day with approximately millisecond accuracy.
-
-    """
-
-    # based on redate.py by David Finlayson.
-
-    if JD < 0:
-        year_offset = int(-JD) // 365 + 1
-        JD += year_offset * 365
-    else:
-        year_offset = 0
-
-    dayofwk = int(math.fmod(int(JD + 1.5), 7))
-    (F, Z) = math.modf(JD + 0.5)
-    Z = int(Z)
-    A = Z
-    B = A + 1524
-    C = int((B - 122.1) / 365.)
-    D = int(365. * C)
-    E = int((B - D) / 30.6001)
-
-    # Convert to date
-    day = B - D - int(30.6001 * E) + F
-    nday = B - D - 123
-    if nday <= 305:
-        dayofyr = nday + 60
-    else:
-        dayofyr = nday - 305
-    if E < 14:
-        month = E - 1
-    else:
-        month = E - 13
-
-    if month > 2:
-        year = C - 4716
-    else:
-        year = C - 4715
-
-    # Convert fractions of a day to time
-    (dfrac, days) = math.modf(day / 1.0)
-    (hfrac, hours) = math.modf(dfrac * 24.0)
-    (mfrac, minutes) = math.modf(hfrac * 60.0)
-    (sfrac, seconds) = math.modf(mfrac * 60.0)
-    microseconds = sfrac*1.e6
-
-    if year_offset > 0:
-        # correct dayofwk
-
-        # 365 mod 7 = 1, so the day of the week changes by one day for
-        # every year in year_offset
-        dayofwk -= int(math.fmod(year_offset, 7))
-
-        if dayofwk < 0:
-            dayofwk += 7
-
-    return DatetimeNoLeap(year - year_offset, month, int(days), int(hours), int(minutes),
-                          int(seconds), int(microseconds),dayofwk, dayofyr)
-
-
-cdef _DateFromAllLeap(JD):
-    """
-
-returns a 'datetime-like' object given Julian Day for a calendar where all
-years have 366 days.
-Julian Day is a fractional day with approximately millisecond accuracy.
-
-    """
-
-    # based on redate.py by David Finlayson.
-
-    if JD < 0:
-        raise ValueError('Julian Day must be positive')
-
-    dayofwk = int(math.fmod(int(JD + 1.5), 7))
-    (F, Z) = math.modf(JD + 0.5)
-    Z = int(Z)
-    A = Z
-    B = A + 1524
-    C = int((B - 122.1) / 366.)
-    D = int(366. * C)
-    E = int((B - D) / 30.6001)
-
-    # Convert to date
-    day = B - D - int(30.6001 * E) + F
-    nday = B - D - 123
-    if nday <= 305:
-        dayofyr = nday + 60
-    else:
-        dayofyr = nday - 305
-    if E < 14:
-        month = E - 1
-    else:
-        month = E - 13
-    if month > 2:
-        dayofyr = dayofyr + 1
-
-    if month > 2:
-        year = C - 4716
-    else:
-        year = C - 4715
-
-    # Convert fractions of a day to time
-    (dfrac, days) = math.modf(day / 1.0)
-    (hfrac, hours) = math.modf(dfrac * 24.0)
-    (mfrac, minutes) = math.modf(hfrac * 60.0)
-    (sfrac, seconds) = math.modf(mfrac * 60.0)
-    microseconds = sfrac*1.e6
-
-    return DatetimeAllLeap(year, month, int(days), int(hours), int(minutes),
-                           int(seconds), int(microseconds),dayofwk, dayofyr)
-
-
-cdef _DateFrom360Day(JD):
-    """
-
-returns a 'datetime-like' object given Julian Day for a calendar where all
-months have 30 days.
-Julian Day is a fractional day with approximately millisecond accuracy.
-
-    """
+        if return_tuple:
+            return np.array([args for args in
+                            zip(year, month, day, hour, minute, second,
+                                microsecond,dayofwk,dayofyr)])
+        else:
+            if is_real_datetime:
+                return np.array([datetime_type(*args)
+                                 for args in
+                                 zip(year, month, day, hour, minute, second,
+                                     microsecond)])
+            else:
+                return np.array([datetime_type(*args)
+                                 for args in
+                                 zip(year, month, day, hour, minute, second,
+                                     microsecond,dayofwk,dayofyr)])
 
-    if JD < 0:
-        year_offset = int(-JD) // 360 + 1
-        JD += year_offset * 360
     else:
-        year_offset = 0
-
-    #jd = int(360. * (year + 4716)) + int(30. * (month - 1)) + day
-    (F, Z) = math.modf(JD)
-    year = int((Z - 0.5) / 360.) - 4716
-    dayofyr = Z - (year + 4716) * 360
-    month = int((dayofyr - 0.5) / 30) + 1
-    day = dayofyr - (month - 1) * 30 + F
-
-    # Convert fractions of a day to time
-    (dfrac, days) = math.modf(day / 1.0)
-    (hfrac, hours) = math.modf(dfrac * 24.0)
-    (mfrac, minutes) = math.modf(hfrac * 60.0)
-    (sfrac, seconds) = math.modf(mfrac * 60.0)
-    microseconds = sfrac*1.e6
-
-    return Datetime360Day(year - year_offset, month, int(days), int(hours), int(minutes),
-                          int(seconds), int(microseconds), -1, dayofyr)
-
+        if return_tuple:
+            return (year[0], month[0], day[0], hour[0],
+                    minute[0], second[0], microsecond[0],
+                    dayofwk[0], dayofyr[0])
+        else:
+            if is_real_datetime:
+                return datetime_type(year[0], month[0], day[0], hour[0],
+                                     minute[0], second[0], microsecond[0])
+            else:
+                return datetime_type(year[0], month[0], day[0], hour[0],
+                                     minute[0], second[0], microsecond[0],
+                                     dayofwk[0], dayofyr[0])
 
 class utime:
 
@@ -880,7 +582,8 @@ C{'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 C{'hours
-since 0001-01-01 00:00:00'}.
+since 0001-01-01 00:00:00'}. months is allowed as a time unit
+*only* for the 360_day calendar.
 
 The B{C{calendar}} keyword describes the calendar used in the time calculations.
 All the values currently defined in the U{CF metadata convention
@@ -974,7 +677,8 @@ C{'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 C{'hours
-since 0001-01-01 00:00:00'}.
+since 0001-01-01 00:00:00'}. months is allowed as a time unit
+*only* for the 360_day calendar.
 
 @keyword calendar: describes the calendar used in the time calculations.
 All the values currently defined in the U{CF metadata convention
@@ -1012,16 +716,14 @@ units to datetime objects.
         else:
             raise ValueError(
                 "calendar must be one of %s, got '%s'" % (str(_calendars), calendar))
-        units, tzoffset, self.origin = _parse_date_and_units(unit_string)
+        units, tzoffset, self.origin =\
+        _parse_date_and_units(unit_string,calendar)
         # real-world calendars limited to positive reference years.
         if self.calendar in ['julian', 'standard', 'gregorian', 'proleptic_gregorian']:
             if self.origin.year == 0:
                 msg='zero not allowed as a reference year, does not exist in Julian or Gregorian calendars'
                 raise ValueError(msg)
-            elif self.origin.year < 0:
-                msg='negative reference year in time units, must be >= 1'
-                raise ValueError(msg)
-        self.tzoffset = tzoffset  # time zone offset in minutes
+        self.tzoffset = np.array(tzoffset,dtype=np.float128)  # time zone offset in minutes
         self.units = units
         self.unit_string = unit_string
         if self.calendar in ['noleap', '365_day'] and self.origin.month == 2 and self.origin.day == 29:
@@ -1030,14 +732,7 @@ units to datetime objects.
         if self.calendar == '360_day' and self.origin.day > 30:
             raise ValueError(
                 'there are only 30 days in every month with the 360_day calendar')
-        if self.calendar in ['noleap', '365_day']:
-            self._jd0 = _NoLeapDayFromDate(self.origin)
-        elif self.calendar in ['all_leap', '366_day']:
-            self._jd0 = _AllLeapFromDate(self.origin)
-        elif self.calendar == '360_day':
-            self._jd0 = _360DayFromDate(self.origin)
-        else:
-            self._jd0 = JulianDayFromDate(self.origin, calendar=self.calendar)
+        self._jd0 = JulianDayFromDate(self.origin, calendar=self.calendar)
         self.only_use_cftime_datetimes = only_use_cftime_datetimes
 
     def date2num(self, date):
@@ -1065,47 +760,14 @@ units to datetime objects.
         except:
             isscalar = True
         if not isscalar:
-            date = numpy.array(date)
+            date = np.array(date)
             shape = date.shape
-        if self.calendar in ['julian', 'standard', 'gregorian', 'proleptic_gregorian']:
-            if isscalar:
-                jdelta = JulianDayFromDate(date, self.calendar) - self._jd0
-            else:
-                jdelta = JulianDayFromDate(
-                    date.flat, self.calendar) - self._jd0
-        elif self.calendar in ['noleap', '365_day']:
-            if isscalar:
-                if date.month == 2 and date.day == 29:
-                    raise ValueError(
-                        'there is no leap day in the noleap calendar')
-                jdelta = _NoLeapDayFromDate(date) - self._jd0
-            else:
-                jdelta = []
-                for d in date.flat:
-                    if d.month == 2 and d.day == 29:
-                        raise ValueError(
-                            'there is no leap day in the noleap calendar')
-                    jdelta.append(_NoLeapDayFromDate(d) - self._jd0)
-        elif self.calendar in ['all_leap', '366_day']:
-            if isscalar:
-                jdelta = _AllLeapFromDate(date) - self._jd0
-            else:
-                jdelta = [_AllLeapFromDate(d) - self._jd0 for d in date.flat]
-        elif self.calendar == '360_day':
-            if isscalar:
-                if date.day > 30:
-                    raise ValueError(
-                        'there are only 30 days in every month with the 360_day calendar')
-                jdelta = _360DayFromDate(date) - self._jd0
-            else:
-                jdelta = []
-                for d in date.flat:
-                    if d.day > 30:
-                        raise ValueError(
-                            'there are only 30 days in every month with the 360_day calendar')
-                    jdelta.append(_360DayFromDate(d) - self._jd0)
+        if isscalar:
+            jdelta = JulianDayFromDate(date, self.calendar)-self._jd0
+        else:
+            jdelta = JulianDayFromDate(date.flat, self.calendar)-self._jd0
         if not isscalar:
-            jdelta = numpy.array(jdelta)
+            jdelta = np.array(jdelta)
         # convert to desired units, add time zone offset.
         if self.units in microsec_units:
             jdelta = jdelta * 86400. * 1.e6  + self.tzoffset * 60. * 1.e6
@@ -1119,12 +781,14 @@ units to datetime objects.
             jdelta = jdelta * 24. + self.tzoffset / 60.
         elif self.units in day_units:
             jdelta = jdelta + self.tzoffset / 1440.
+        elif self.units in month_units and self.calendar == '360_day':
+            jdelta = jdelta/30. + self.tzoffset / (30. * 1440.)
         else:
             raise ValueError('unsupported time units')
         if isscalar:
-            return jdelta
+            return jdelta.astype(np.float64)
         else:
-            return numpy.reshape(jdelta, shape)
+            return np.reshape(jdelta.astype(np.float64), shape)
 
     def num2date(self, time_value):
         """
@@ -1154,11 +818,11 @@ units to datetime objects.
         except:
             isscalar = True
         ismasked = False
-        if numpy.ma.isMA(time_value) and numpy.ma.is_masked(time_value):
+        if np.ma.isMA(time_value) and np.ma.is_masked(time_value):
             mask = time_value.mask
             ismasked = True
         if not isscalar:
-            time_value = numpy.array(time_value, dtype='d')
+            time_value = np.array(time_value, dtype='d')
             shape = time_value.shape
         # convert to desired units, subtract time zone offset.
         if self.units in microsec_units:
@@ -1173,47 +837,34 @@ units to datetime objects.
             jdelta = time_value / 24. - self.tzoffset / 1440.
         elif self.units in day_units:
             jdelta = time_value - self.tzoffset / 1440.
+        elif self.units in month_units and self.calendar == '360_day':
+            # only allowed for 360_day calendar
+            jdelta = time_value * 30. - self.tzoffset / 1440.
         else:
             raise ValueError('unsupported time units')
         jd = self._jd0 + jdelta
-        if self.calendar in ['julian', 'standard', 'gregorian', 'proleptic_gregorian']:
-            if not isscalar:
-                if ismasked:
-                    date = []
-                    for j, m in zip(jd.flat, mask.flat):
-                        if not m:
-                            date.append(DateFromJulianDay(j, self.calendar,
-                                                          self.only_use_cftime_datetimes))
-                        else:
-                            date.append(None)
-                else:
-                    date = DateFromJulianDay(jd.flat, self.calendar,
-                                             self.only_use_cftime_datetimes)
-            else:
-                if ismasked and mask.item():
-                    date = None
-                else:
-                    date = DateFromJulianDay(jd, self.calendar,
-                                             self.only_use_cftime_datetimes)
-        elif self.calendar in ['noleap', '365_day']:
-            if not isscalar:
-                date = [_DateFromNoLeapDay(j) for j in jd.flat]
-            else:
-                date = _DateFromNoLeapDay(jd)
-        elif self.calendar in ['all_leap', '366_day']:
-            if not isscalar:
-                date = [_DateFromAllLeap(j) for j in jd.flat]
+        if not isscalar:
+            if ismasked:
+                date = []
+                for j, m in zip(jd.flat, mask.flat):
+                    if not m:
+                        date.append(DateFromJulianDay(j, self.calendar,
+                                                      self.only_use_cftime_datetimes))
+                    else:
+                        date.append(None)
             else:
-                date = _DateFromAllLeap(jd)
-        elif self.calendar == '360_day':
-            if not isscalar:
-                date = [_DateFrom360Day(j) for j in jd.flat]
+                date = DateFromJulianDay(jd.flat, self.calendar,
+                                         self.only_use_cftime_datetimes)
+        else:
+            if ismasked and mask.item():
+                date = None
             else:
-                date = _DateFrom360Day(jd)
+                date = DateFromJulianDay(jd, self.calendar,
+                                         self.only_use_cftime_datetimes)
         if isscalar:
             return date
         else:
-            return numpy.reshape(numpy.array(date), shape)
+            return np.reshape(np.array(date), shape)
 
 
 cdef _parse_timezone(tzstring):
@@ -1314,23 +965,23 @@ cdef _check_index(indices, times, nctime, calendar, select):
 #       t.append(nctime[ind])
 
     if select == 'exact':
-        return numpy.all(t == times)
+        return np.all(t == times)
 
     elif select == 'before':
-        ta = nctime[numpy.clip(indices + 1, 0, N - 1)]
-        return numpy.all(t <= times) and numpy.all(ta > times)
+        ta = nctime[np.clip(indices + 1, 0, N - 1)]
+        return np.all(t <= times) and np.all(ta > times)
 
     elif select == 'after':
-        tb = nctime[numpy.clip(indices - 1, 0, N - 1)]
-        return numpy.all(t >= times) and numpy.all(tb < times)
+        tb = nctime[np.clip(indices - 1, 0, N - 1)]
+        return np.all(t >= times) and np.all(tb < times)
 
     elif select == 'nearest':
-        ta = nctime[numpy.clip(indices + 1, 0, N - 1)]
-        tb = nctime[numpy.clip(indices - 1, 0, N - 1)]
+        ta = nctime[np.clip(indices + 1, 0, N - 1)]
+        tb = nctime[np.clip(indices - 1, 0, N - 1)]
         delta_after = ta - t
         delta_before = t - tb
-        delta_check = numpy.abs(times - t)
-        return numpy.all(delta_check <= delta_after) and numpy.all(delta_check <= delta_before)
+        delta_check = np.abs(times - t)
+        return np.all(delta_check <= delta_after) and np.all(delta_check <= delta_before)
 
 
 def _date2index(dates, nctime, calendar=None, select='exact'):
@@ -1406,7 +1057,7 @@ def time2index(times, nctime, calendar=None, select='exact'):
     if calendar == None:
         calendar = getattr(nctime, 'calendar', 'standard')
 
-    num = numpy.atleast_1d(times)
+    num = np.atleast_1d(times)
     N = len(nctime)
 
     # Trying to infer the correct index from the starting time and the stride.
@@ -1418,11 +1069,11 @@ def time2index(times, nctime, calendar=None, select='exact'):
         t0 = nctime[0]
         dt = 1.
     if select in ['exact', 'before']:
-        index = numpy.array((num - t0) / dt, int)
+        index = np.array((num - t0) / dt, int)
     elif select == 'after':
-        index = numpy.array(numpy.ceil((num - t0) / dt), int)
+        index = np.array(np.ceil((num - t0) / dt), int)
     else:
-        index = numpy.array(numpy.around((num - t0) / dt), int)
+        index = np.array(np.around((num - t0) / dt), int)
 
     # Checking that the index really corresponds to the given time.
     # If the times do not correspond, then it means that the times
@@ -1431,17 +1082,17 @@ def time2index(times, nctime, calendar=None, select='exact'):
 
         # Use the bisection method. Assumes nctime is ordered.
         import bisect
-        index = numpy.array([bisect.bisect_right(nctime, n) for n in num], int)
+        index = np.array([bisect.bisect_right(nctime, n) for n in num], int)
         before = index == 0
 
-        index = numpy.array([bisect.bisect_left(nctime, n) for n in num], int)
+        index = np.array([bisect.bisect_left(nctime, n) for n in num], int)
         after = index == N
 
-        if select in ['before', 'exact'] and numpy.any(before):
+        if select in ['before', 'exact'] and np.any(before):
             raise ValueError(
                 'Some of the times given are before the first time in `nctime`.')
 
-        if select in ['after', 'exact'] and numpy.any(after):
+        if select in ['after', 'exact'] and np.any(after):
             raise ValueError(
                 'Some of the times given are after the last time in `nctime`.')
 
@@ -1449,8 +1100,8 @@ def time2index(times, nctime, calendar=None, select='exact'):
         # Use list comprehension instead of the simpler `nctime[index]` since
         # not all time objects support numpy integer indexing (eg dap).
         index[after] = N - 1
-        ncnum = numpy.squeeze([nctime[i] for i in index])
-        mismatch = numpy.nonzero(ncnum != num)[0]
+        ncnum = np.squeeze([nctime[i] for i in index])
+        mismatch = np.nonzero(ncnum != num)[0]
 
         if select == 'exact':
             if len(mismatch) > 0:
@@ -1465,7 +1116,7 @@ def time2index(times, nctime, calendar=None, select='exact'):
             pass
 
         elif select == 'nearest':
-            nearest_to_left = num[mismatch] < numpy.array(
+            nearest_to_left = num[mismatch] < np.array(
                 [float(nctime[i - 1]) + float(nctime[i]) for i in index[mismatch]]) / 2.
             index[mismatch] = index[mismatch] - 1 * nearest_to_left
 
@@ -1526,7 +1177,7 @@ Gregorial calendar.
         self.day = day
         self.hour = hour
         self.minute = minute
-        self.dayofwk = dayofwk
+        self.dayofwk = dayofwk # 0 is Monday, 6 is Sunday
         self.dayofyr = dayofyr
         self.second = second
         self.microsecond = microsecond
@@ -1615,13 +1266,23 @@ Gregorial calendar.
                 # utime.date2num(), but this implementation does
                 # not attempt it.
                 raise TypeError("cannot compare {0!r} and {1!r} (different calendars)".format(dt, dt_other))
-        elif isinstance(other, real_datetime):
+        elif isinstance(other, datetime_python):
             # comparing datetime and real_datetime
             if not dt.datetime_compatible:
                 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:
-            raise TypeError("cannot compare {0!r} and {1!r}".format(self, other))
+            # With Python3 we can use "return NotImplemented". If the other
+            # object does not have rich comparison instructions for cftime
+            # then a TypeError is automatically raised. With Python2 in this
+            # scenario the default behaviour is to compare the object ids
+            # which will always have a result. Therefore there is no way to
+            # differentiate between objects that do or do not have legitimate
+            # comparisons, and so we cannot remove the TypeError below.
+            if sys.version_info[0] < 3:
+                raise TypeError("cannot compare {0!r} and {1!r}".format(self, other))
+            else:
+                return NotImplemented
 
     cdef _getstate(self):
         return (self.year, self.month, self.day, self.hour,
@@ -1659,7 +1320,7 @@ Gregorial calendar.
                     raise ValueError("cannot compute the time difference between dates that are not calendar-aware")
                 converter = _converters[dt.calendar]
                 return timedelta(seconds=converter.date2num(dt) - converter.date2num(other))
-            elif isinstance(other, real_datetime):
+            elif isinstance(other, datetime_python):
                 # datetime - real_datetime
                 if not dt.datetime_compatible:
                     raise ValueError("cannot compute the time difference between dates with different calendars")
@@ -1670,7 +1331,7 @@ Gregorial calendar.
             else:
                 return NotImplemented
         else:
-            if isinstance(self, real_datetime):
+            if isinstance(self, datetime_python):
                 # real_datetime - datetime
                 if not other.datetime_compatible:
                     raise ValueError("cannot compute the time difference between dates with different calendars")
@@ -1688,7 +1349,14 @@ but uses the "noleap" ("365_day") calendar.
         datetime.__init__(self, *args, **kwargs)
         self.calendar = "noleap"
         self.datetime_compatible = False
-        assert_valid_date(self, no_leap, False)
+        assert_valid_date(self, no_leap, False, has_year_zero=True)
+        # if dayofwk, dayofyr not set, calculate them.
+        if self.dayofwk < 0:
+            jd = JulianDayFromDate(self,calendar='365_day')
+            year,month,day,hour,mn,sec,ms,dayofwk,dayofyr =\
+            DateFromJulianDay(jd,return_tuple=True,calendar='365_day')
+            self.dayofwk = dayofwk
+            self.dayofyr = dayofyr
 
     cdef _add_timedelta(self, delta):
         return DatetimeNoLeap(*add_timedelta(self, delta, no_leap, False))
@@ -1703,7 +1371,14 @@ but uses the "all_leap" ("366_day") calendar.
         datetime.__init__(self, *args, **kwargs)
         self.calendar = "all_leap"
         self.datetime_compatible = False
-        assert_valid_date(self, all_leap, False)
+        assert_valid_date(self, all_leap, False, has_year_zero=True)
+        # if dayofwk, dayofyr not set, calculate them.
+        if self.dayofwk < 0:
+            jd = JulianDayFromDate(self,calendar='366_day')
+            year,month,day,hour,mn,sec,ms,dayofwk,dayofyr =\
+            DateFromJulianDay(jd,return_tuple=True,calendar='366_day')
+            self.dayofwk = dayofwk
+            self.dayofyr = dayofyr
 
     cdef _add_timedelta(self, delta):
         return DatetimeAllLeap(*add_timedelta(self, delta, all_leap, False))
@@ -1718,7 +1393,14 @@ but uses the "360_day" calendar.
         datetime.__init__(self, *args, **kwargs)
         self.calendar = "360_day"
         self.datetime_compatible = False
-        assert_valid_date(self, no_leap, False, is_360_day=True)
+        assert_valid_date(self, no_leap, False, has_year_zero=True, is_360_day=True)
+        # if dayofwk, dayofyr not set, calculate them.
+        if self.dayofwk < 0:
+            jd = JulianDayFromDate(self,calendar='360_day')
+            year,month,day,hour,mn,sec,ms,dayofwk,dayofyr =\
+            DateFromJulianDay(jd,return_tuple=True,calendar='360_day')
+            self.dayofwk = dayofwk
+            self.dayofyr = dayofyr
 
     cdef _add_timedelta(self, delta):
         return Datetime360Day(*add_timedelta_360_day(self, delta))
@@ -1734,6 +1416,13 @@ but uses the "julian" calendar.
         self.calendar = "julian"
         self.datetime_compatible = False
         assert_valid_date(self, is_leap_julian, False)
+        # if dayofwk, dayofyr not set, calculate them.
+        if self.dayofwk < 0:
+            jd = JulianDayFromDate(self,calendar='julian')
+            year,month,day,hour,mn,sec,ms,dayofwk,dayofyr =\
+            DateFromJulianDay(jd,return_tuple=True,calendar='julian')
+            self.dayofwk = dayofwk
+            self.dayofyr = dayofyr
 
     cdef _add_timedelta(self, delta):
         return DatetimeJulian(*add_timedelta(self, delta, is_leap_julian, False))
@@ -1763,6 +1452,13 @@ a datetime.datetime instance or vice versa.
         else:
             self.datetime_compatible = False
         assert_valid_date(self, is_leap_gregorian, True)
+        # if dayofwk, dayofyr not set, calculate them.
+        if self.dayofwk < 0:
+            jd = JulianDayFromDate(self,calendar='gregorian')
+            year,month,day,hour,mn,sec,ms,dayofwk,dayofyr =\
+            DateFromJulianDay(jd,return_tuple=True,calendar='gregorian')
+            self.dayofwk = dayofwk
+            self.dayofyr = dayofyr
 
     cdef _add_timedelta(self, delta):
         return DatetimeGregorian(*add_timedelta(self, delta, is_leap_gregorian, True))
@@ -1790,6 +1486,13 @@ format, and calendar.
         self.calendar = "proleptic_gregorian"
         self.datetime_compatible = True
         assert_valid_date(self, is_leap_proleptic_gregorian, False)
+        # if dayofwk, dayofyr not set, calculate them.
+        if self.dayofwk < 0:
+            jd = JulianDayFromDate(self,calendar='proleptic_gregorian')
+            year,month,day,hour,mn,sec,ms,dayofwk,dayofyr =\
+            DateFromJulianDay(jd,return_tuple=True,calendar='proleptic_gregorian')
+            self.dayofwk = dayofwk
+            self.dayofyr = dayofyr
 
     cdef _add_timedelta(self, delta):
         return DatetimeProlepticGregorian(*add_timedelta(self, delta,
@@ -1851,18 +1554,15 @@ cdef _strftime(datetime dt, fmt):
 
 cdef bint is_leap_julian(int year):
     "Return 1 if year is a leap year in the Julian calendar, 0 otherwise."
-    cdef int y
-    y = year if year > 0 else year + 1
-    return (y % 4) == 0
+    return _is_leap(year, calendar='julian')
 
 cdef bint is_leap_proleptic_gregorian(int year):
-    "Return 1 if year is a leap year in the Gregorian calendar, 0 otherwise."
-    cdef int y
-    y = year if year > 0 else year + 1
-    return (((y % 4) == 0) and ((y % 100) != 0)) or ((y % 400) == 0)
+    "Return 1 if year is a leap year in the Proleptic Gregorian calendar, 0 otherwise."
+    return _is_leap(year, calendar='proleptic_gregorian')
 
 cdef bint is_leap_gregorian(int year):
-    return (year > 1582 and is_leap_proleptic_gregorian(year)) or (year < 1582 and is_leap_julian(year))
+    "Return 1 if year is a leap year in the Gregorian calendar, 0 otherwise."
+    return _is_leap(year, calendar='standard')
 
 cdef bint all_leap(int year):
     "Return True for all years."
@@ -1872,40 +1572,30 @@ cdef bint no_leap(int year):
     "Return False for all years."
     return False
 
-# numbers of days per month for calendars supported by add_timedelta(...)
-cdef int[13] month_lengths_365_day, month_lengths_366_day
-#                  Dummy Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
-for j,N in enumerate([-1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]):
-    month_lengths_365_day[j] = N
-
-#                  Dummy Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
-for j,N in enumerate([-1, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]):
-    month_lengths_366_day[j] = N
-
-cdef int* month_lengths(bint (*is_leap)(int), int year):
+cdef int * month_lengths(bint (*is_leap)(int), int year):
     if is_leap(year):
-        return month_lengths_366_day
+        return _dpm_leap
     else:
-        return month_lengths_365_day
+        return _dpm
 
 cdef void assert_valid_date(datetime dt, bint (*is_leap)(int),
                             bint julian_gregorian_mixed,
+                            bint has_year_zero=False,
                             bint is_360_day=False) except *:
-    cdef int[13] month_length
+    cdef int[12] month_length
 
-    if not is_360_day:
+    if not has_year_zero:
         if dt.year == 0:
             raise ValueError("invalid year provided in {0!r}".format(dt))
-        month_length = month_lengths(is_leap, dt.year)
+    if is_360_day:
+        month_length = _dpm_360
     else:
-        for j, N in enumerate(
-                [-1, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30]):
-            month_length[j] = N
+        month_length = month_lengths(is_leap, dt.year)
 
     if dt.month < 1 or dt.month > 12:
         raise ValueError("invalid month provided in {0!r}".format(dt))
 
-    if dt.day < 1 or dt.day > month_length[dt.month]:
+    if dt.day < 1 or dt.day > month_length[dt.month-1]:
         raise ValueError("invalid day number provided in {0!r}".format(dt))
 
     if julian_gregorian_mixed and dt.year == 1582 and dt.month == 10 and dt.day > 4 and dt.day < 15:
@@ -1986,7 +1676,7 @@ cdef tuple add_timedelta(datetime dt, delta, bint (*is_leap)(int), bint julian_g
                 if year == 0:
                     year = -1
                 month_length = month_lengths(is_leap, year)
-            day = month_length[month]
+            day = month_length[month-1]
         else:
             day += delta_days
             delta_days = 0
@@ -1994,8 +1684,8 @@ cdef tuple add_timedelta(datetime dt, delta, bint (*is_leap)(int), bint julian_g
     while delta_days > 0:
         if year == 1582 and month == 10 and day < 5 and day + delta_days > 4:
             delta_days += n_invalid_dates    # skip over invalid dates
-        if day + delta_days > month_length[month]:
-            delta_days -= month_length[month] - (day - 1)
+        if day + delta_days > month_length[month-1]:
+            delta_days -= month_length[month-1] - (day - 1)
             # increment month
             month += 1
             if month > 12:
@@ -2053,3 +1743,306 @@ 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):
+    cdef int tyear
+    cdef bint leap
+    calendar = _check_calendar(calendar)
+    if year == 0:
+        raise ValueError('year zero does not exist in the %s calendar' %\
+                calendar)
+    # Because there is no year 0 in the Julian calendar, years -1, -5, -9, etc
+    # are leap years.
+    if year < 0:
+        tyear = year + 1
+    else:
+        tyear = year
+    if calendar == 'proleptic_gregorian' or (calendar == 'standard' and year > 1581):
+        if tyear % 4: # not divisible by 4
+            leap = False
+        elif year % 100: # not divisible by 100
+            leap = True
+        elif year % 400: # not divisible by 400
+            leap = False
+        else:
+            leap = True
+    elif calendar == 'julian' or (calendar == 'standard' and year < 1582):
+        leap = tyear % 4 == 0
+    elif calendar == '366_day':
+        leap = True
+    else:
+        leap = False
+    return leap
+
+cdef _IntJulianDayFromDate(int year,int month,int day,calendar,skip_transition=False):
+    """Compute integer Julian Day from year,month,day and calendar.
+
+    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'
+
+    Negative years allowed back to -4714
+    (proleptic_gregorian) or -4713 (standard or gregorian calendar).
+
+    Negative year values are allowed in 360_day,365_day,366_day calendars.
+
+    Integer julian day is number of days since noon UTC -4713-1-1
+    in the julian or mixed julian/gregorian calendar, or noon UTC
+    -4714-11-24 in the proleptic_gregorian calendar. Reference
+    date is noon UTC 0-1-1 for other calendars.
+
+    There is no year zero in standard (mixed), julian, or proleptic_gregorian
+    calendars.
+
+    Subtract 0.5 to get 00 UTC on that day.
+
+    optional kwarg 'skip_transition':  When True, leave 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 jday, jday_jul, jday_greg
+    cdef bint leap
+    cdef int[12] dpm2use
+
+    # validate inputs.
+    calendar = _check_calendar(calendar)
+    if month < 1 or month > 12 or day < 1 or day > 31:
+        msg = "date %04d-%02d-%02d does not exist in the %s calendar" %\
+        (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)
+    elif calendar == '365_day':
+        return _IntJulianDayFromDate_365day(year,month,day)
+    elif calendar == '366_day':
+        return _IntJulianDayFromDate_366day(year,month,day)
+
+    # handle standard, julian, proleptic_gregorian calendars.
+    if year == 0:
+        raise ValueError('year zero does not exist in the %s calendar' %\
+                calendar)
+    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)
+    if not leap and month == 2 and day == 29:
+        raise ValueError('%s is not a leap year' % year)
+
+    # add year offset
+    if year < 0:
+        year += 4801
+    else:
+        year += 4800
+
+    if leap:
+        dpm2use = _dpm_leap
+    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_jul = jday + 365*(year-1) + (year-1)//4
+    jday_jul -= 31777 # fix year offset
+    if calendar == 'julian':
+        return jday_jul
+    elif calendar == 'proleptic_gregorian':
+        return jday_greg
+    elif calendar == 'standard':
+        # 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')
+        if jday_jul < 2299161: # 1582 October 15
+            return jday_jul
+        else:
+            if skip_transition:
+                return jday_greg+10
+            else:
+                return jday_greg
+
+    return jday
+
+cdef _IntJulianDayToDate(int jday,calendar,skip_transition=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:
+       yp1 = 1 # no year 0
+    tjday = _IntJulianDayFromDate(yp1,1,1,calendar,skip_transition=True)
+    while jday >= tjday:
+        year += 1
+        if year == 0:
+            year = 1
+        yp1 = year + 1
+        if yp1 == 0:
+            yp1 = 1
+        tjday = _IntJulianDayFromDate(yp1,1,1,calendar,skip_transition=True)
+    if _is_leap(year, calendar):
+        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)
+    while jday > tjday:
+        month += 1
+        tjday =\
+        _IntJulianDayFromDate(year,month,dpm2use[month-1],calendar,skip_transition=True)
+    tjday = _IntJulianDayFromDate(year,month,1,calendar,skip_transition=True)
+    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


=====================================
debian/changelog
=====================================
@@ -1,8 +1,10 @@
-cftime (1.0.1-2) UNRELEASED; urgency=medium
+cftime (1.0.2-1) unstable; urgency=medium
 
+  * New upstream release.
   * Bump Standards-Version to 4.2.1, no changes.
+  * Update copyright file to include GPL-3+ for calcalcs code.
 
- -- Bas Couwenberg <sebastic at debian.org>  Tue, 28 Aug 2018 09:48:42 +0200
+ -- Bas Couwenberg <sebastic at debian.org>  Sat, 27 Oct 2018 10:03:04 +0200
 
 cftime (1.0.1-1) unstable; urgency=medium
 


=====================================
debian/copyright
=====================================
@@ -6,8 +6,11 @@ Source: https://github.com/Unidata/cftime
 Files: *
 Copyright: 2008, Jeffrey Whitaker
            2007, Michael Twomey
+           2010, David W. Pierce
 Comment: Parts of pyiso8601 are included under the MIT license.
-License: ISC and Expat
+ 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+
 
 Files: debian/*
 Copyright: 2018, Bas Couwenberg <sebastic at debian.org>
@@ -48,3 +51,17 @@ License: Expat
  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'.


=====================================
test/benchmark.py
=====================================
@@ -0,0 +1,17 @@
+from cftime import num2date, date2num
+import time
+import numpy as np
+units = 'hours since 01-01-01'
+calendar = 'standard'
+timevals = np.arange(0,10000,1)
+print('processing %s values...' % len(timevals))
+t1 = time.clock()
+dates =\
+num2date(timevals,units=units,calendar=calendar,only_use_cftime_datetimes=True)
+t2 = time.clock()
+t = t2-t1
+print('num2date took %s seconds' % t)
+timevals2 = date2num(dates,units=units,calendar=calendar)
+t1 = time.clock()
+t = t1-t2
+print('date2num took %s seconds' % t)


=====================================
test/test_cftime.py
=====================================
@@ -1,3 +1,4 @@
+from __future__ import print_function
 import copy
 import unittest
 from collections import namedtuple
@@ -8,11 +9,13 @@ import pytest
 from numpy.testing import assert_almost_equal, assert_equal
 
 from cftime import datetime as datetimex
+from cftime import real_datetime
 from cftime import (DateFromJulianDay, Datetime360Day, DatetimeAllLeap,
                     DatetimeGregorian, DatetimeJulian, DatetimeNoLeap,
                     DatetimeProlepticGregorian, JulianDayFromDate, _parse_date,
                     date2index, date2num, num2date, utime)
 import cftime
+
 # test cftime module for netCDF time <--> python datetime conversions.
 
 dtime = namedtuple('dtime', ('values', 'units', 'calendar'))
@@ -333,73 +336,104 @@ class cftimeTestCase(unittest.TestCase):
         dateformat =  '%Y-%m-%d %H:%M:%S'
         dateref = datetime(2015,2,28,12)
         ntimes = 1001
+        verbose = True # print out max error diagnostics
         for calendar in calendars:
-            eps = 100.
-            units = 'microseconds since 1800-01-30 01:01:01'
+            eps = 10.
+            units = 'microseconds since 2000-01-30 01:01:01'
             microsecs1 = date2num(dateref,units,calendar=calendar)
+            maxerr = 0
             for n in range(ntimes):
                 microsecs1 += 1.
                 date1 = num2date(microsecs1, units, calendar=calendar)
                 microsecs2 = date2num(date1, units, calendar=calendar)
                 date2 = num2date(microsecs2, units, calendar=calendar)
                 err = np.abs(microsecs1 - microsecs2)
+                maxerr = max(err,maxerr)
                 assert(err < eps)
                 assert(date1.strftime(dateformat) == date2.strftime(dateformat))
+            if verbose:
+                print('calender = %s max abs err (microsecs) = %s eps = %s' % \
+                     (calendar,maxerr,eps))
             units = 'milliseconds since 1800-01-30 01:01:01'
-            eps = 0.1
+            eps = 0.01
             millisecs1 = date2num(dateref,units,calendar=calendar)
+            maxerr = 0.
             for n in range(ntimes):
                 millisecs1 += 0.001
                 date1 = num2date(millisecs1, units, calendar=calendar)
                 millisecs2 = date2num(date1, units, calendar=calendar)
                 date2 = num2date(millisecs2, units, calendar=calendar)
                 err = np.abs(millisecs1 - millisecs2)
+                maxerr = max(err,maxerr)
                 assert(err < eps)
                 assert(date1.strftime(dateformat) == date2.strftime(dateformat))
+            if verbose:
+                print('calender = %s max abs err (millisecs) = %s eps = %s' % \
+                     (calendar,maxerr,eps))
             eps = 1.e-4
             units = 'seconds since 0001-01-30 01:01:01'
             secs1 = date2num(dateref,units,calendar=calendar)
+            maxerr = 0.
             for n in range(ntimes):
                 secs1 += 0.1
                 date1 = num2date(secs1, units, calendar=calendar)
                 secs2 = date2num(date1, units, calendar=calendar)
                 date2 = num2date(secs2, units, calendar=calendar)
                 err = np.abs(secs1 - secs2)
+                maxerr = max(err,maxerr)
                 assert(err < eps)
                 assert(date1.strftime(dateformat) == date2.strftime(dateformat))
-            eps = 1.e-5
+            if verbose:
+                print('calender = %s max abs err (secs) = %s eps = %s' % \
+                     (calendar,maxerr,eps))
+            eps = 1.e-6
             units = 'minutes since 0001-01-30 01:01:01'
             mins1 = date2num(dateref,units,calendar=calendar)
+            maxerr = 0.
             for n in range(ntimes):
                 mins1 += 0.01
                 date1 = num2date(mins1, units, calendar=calendar)
                 mins2 = date2num(date1, units, calendar=calendar)
                 date2 = num2date(mins2, units, calendar=calendar)
                 err = np.abs(mins1 - mins2)
+                maxerr = max(err,maxerr)
                 assert(err < eps)
                 assert(date1.strftime(dateformat) == date2.strftime(dateformat))
-            eps = 1.e-5
+            if verbose:
+                print('calender = %s max abs err (mins) = %s eps = %s' % \
+                     (calendar,maxerr,eps))
+            eps = 1.e-7
             units = 'hours since 0001-01-30 01:01:01'
             hrs1 = date2num(dateref,units,calendar=calendar)
+            maxerr = 0.
             for n in range(ntimes):
                 hrs1 += 0.001
                 date1 = num2date(hrs1, units, calendar=calendar)
                 hrs2 = date2num(date1, units, calendar=calendar)
                 date2 = num2date(hrs2, units, calendar=calendar)
                 err = np.abs(hrs1 - hrs2)
+                maxerr = max(err,maxerr)
                 assert(err < eps)
                 assert(date1.strftime(dateformat) == date2.strftime(dateformat))
-            eps = 1.e-5
+            if verbose:
+                print('calender = %s max abs err (hours) = %s eps = %s' % \
+                     (calendar,maxerr,eps))
+            eps = 1.e-9
             units = 'days since 0001-01-30 01:01:01'
             days1 = date2num(dateref,units,calendar=calendar)
+            maxerr = 0.
             for n in range(ntimes):
                 days1 += 0.00001
                 date1 = num2date(days1, units, calendar=calendar)
                 days2 = date2num(date1, units, calendar=calendar)
                 date2 = num2date(days2, units, calendar=calendar)
                 err = np.abs(days1 - days2)
+                maxerr = max(err,maxerr)
                 assert(err < eps)
                 assert(date1.strftime(dateformat) == date2.strftime(dateformat))
+            if verbose:
+                print('calender = %s max abs err (days) = %s eps = %s' % \
+                     (calendar,maxerr,eps))
 
         # issue 353
         assert (num2date(0, 'hours since 2000-01-01 0') ==
@@ -468,7 +502,7 @@ class cftimeTestCase(unittest.TestCase):
             pass
         # this should not fail (year zero allowed in 'fake' calendars)
         t = date2num(datetime(1, 1, 1), units, calendar='360_day')
-        self.assertEqual(t, 360)
+        self.assertAlmostEqual(t,360)
         d = num2date(t, units, calendar='360_day')
         self.assertEqual(d, Datetime360Day(1,1,1))
         d = num2date(0, units, calendar='360_day')
@@ -561,6 +595,76 @@ class cftimeTestCase(unittest.TestCase):
         n = date2num(utc_date, units, calendar="julian")
         # n should always be 0 as all units refer to the same point in time
         assert_almost_equal(n, 0)
+        # cftime issue #49
+        d = DateFromJulianDay(2450022.5, "standard")
+        assert (d.year == 1995)
+        assert (d.month == 11)
+        assert (d.day == 1)
+        assert (d.hour == 0)
+        assert (d.minute == 0)
+        assert (d.second == 0)
+        # cftime issue #52
+        d = DateFromJulianDay(1684958.5,calendar='gregorian')
+        assert (d.year == -100)
+        assert (d.month == 3)
+        assert (d.day == 2)
+        assert (d.hour == 0)
+        assert (d.minute == 0)
+        assert (d.second == 0)
+        d = DateFromJulianDay(1684958.5,calendar='standard')
+        assert (d.year == -100)
+        assert (d.month == 3)
+        assert (d.day == 2)
+        assert (d.hour == 0)
+        assert (d.minute == 0)
+        assert (d.second == 0)
+        # test dayofwk, dayofyr attribute setting (cftime issue #13)
+        d1 = DatetimeGregorian(2020,2,29)
+        d2 = real_datetime(2020,2,29)
+        assert (d1.dayofwk == d2.dayofwk == 5)
+        assert (d1.dayofyr == d2.dayofyr == 60)
+        d1 = DatetimeGregorian(2020,2,29,23,59,59)
+        d2 = real_datetime(2020,2,29,23,59,59)
+        assert (d1.dayofwk == d2.dayofwk == 5)
+        assert (d1.dayofyr == d2.dayofyr == 60)
+        d1 = DatetimeGregorian(2020,2,28,23,59,59)
+        d2 = real_datetime(2020,2,28,23,59,59)
+        assert (d1.dayofwk == d2.dayofwk == 4)
+        assert (d1.dayofyr == d2.dayofyr == 59)
+        d1 = DatetimeGregorian(1700,1,1)
+        d2 = real_datetime(1700,1,1)
+        assert (d1.dayofwk == d2.dayofwk == 4)
+        assert (d1.dayofyr == d2.dayofyr == 1)
+        # last day of Julian Calendar (Thursday)
+        d1 = DatetimeJulian(1582, 10, 4, 12)
+        d2 = DatetimeGregorian(1582, 10, 4, 12)
+        assert (d1.dayofwk == d2.dayofwk == 3)
+        assert (d1.dayofyr == d2.dayofyr == 277)
+        # Monday in proleptic gregorian calendar
+        d1 = DatetimeProlepticGregorian(1582, 10, 4, 12)
+        d2 = real_datetime(1582,10,4,12)
+        assert (d1.dayofwk == d2.dayofwk == 0)
+        assert (d1.dayofyr == d2.dayofyr == 277)
+        # issue 71: negative reference years
+        # https://coastwatch.pfeg.noaa.gov/erddap/convert/time.html
+        # gives 2446433 (365 days more - is it counting year 0?)
+        # however http://aa.usno.navy.mil/data/docs/JulianDate.php gives
+        # 2446068, which agrees with us
+        units = "days since -4713-01-01T00:00:00Z"
+        t = date2num(datetime(1985,1,2), units, calendar="standard")
+        assert_almost_equal(t, 2446068)
+
+        # issue #68: allow months since for 360_day calendar
+        d = num2date(1, 'months since 0000-01-01 00:00:00', calendar='360_day')
+        self.assertEqual(d, Datetime360Day(0,2,1))
+        t = date2num(d, 'months since 0000-01-01 00:00:00', calendar='360_day')
+        self.assertEqual(t, 1)
+        # check that exception is raised if 'months since' used with
+        # anything but the 360_day calendar.
+        self.assertRaises(ValueError, num2date, \
+             1, 'months since 01-01-01',calendar='standard')
+        self.assertRaises(ValueError, utime, \
+            'months since 01-01-01', calendar='standard')
 
 
 class TestDate2index(unittest.TestCase):
@@ -745,7 +849,6 @@ class TestDate2index(unittest.TestCase):
         # calculation of nearest index when sum of adjacent
         # time values won't fit in 32 bits.
         query_time = datetime(2037, 1, 3, 21, 12)
-        print(self.time_vars['time3'])
         index = date2index(query_time, self.time_vars['time3'],
                            select='nearest')
         assert(index == 11)
@@ -775,8 +878,9 @@ class issue584TestCase(unittest.TestCase):
         converter = self.converters["noleap"]
 
         # Pick the date corresponding to the Julian day of 1.0 to test
-        # the transision from positive to negative Julian days.
+        # the transition from positive to negative Julian days.
         julian_day = converter.date2num(datetimex(-4712, 1, 2, 12))
+        # should be a Tuesday
 
         old_date = converter.num2date(julian_day)
         for delta_year in range(1, 101): # 100 years cover several 7-year cycles
@@ -1043,13 +1147,13 @@ class issue17TestCase(unittest.TestCase):
 
 class issue57TestCase(unittest.TestCase):
     """Regression tests for issue #57."""
-    # issue 57: cftime._cftime._dateparse returns quite opaque error messages that make it difficult to 
+    # issue 57: cftime._cftime._dateparse returns quite opaque error messages that make it difficult to
     # track down the source of problem
     def setUp(self):
         pass
 
     def test_parse_incorrect_unitstring(self):
-        for datestr in ("days since2017-05-01 ", "dayssince 2017-05-01 00:00", "days snce 2017-05-01 00:00", "days_since_2017-05-01 00:00", 
+        for datestr in ("days since2017-05-01 ", "dayssince 2017-05-01 00:00", "days snce 2017-05-01 00:00", "days_since_2017-05-01 00:00",
             "days_since_2017-05-01_00:00"):
             self.assertRaises(
                 ValueError, cftime._cftime._dateparse, datestr)
@@ -1097,8 +1201,8 @@ def days_per_month_leap_year(date_type, month):
 
 
 def test_zero_year(date_type):
-    # Year 0 is valid in the 360 day calendar
-    if date_type is Datetime360Day:
+    # Year 0 is valid in the 360,365 and 366 day calendars
+    if date_type in [DatetimeNoLeap, DatetimeAllLeap, Datetime360Day]:
         date_type(0, 1, 1)
     else:
         with pytest.raises(ValueError):
@@ -1251,9 +1355,11 @@ def test_num2date_only_use_cftime_datetimes_post_gregorian(
 
 def test_repr():
     expected = 'cftime.datetime(2000, 1, 1, 0, 0, 0, 0, -1, 1)'
+    # dayofwk, dayofyr not set
     assert repr(datetimex(2000, 1, 1)) == expected
 
-    expected = 'cftime.DatetimeGregorian(2000, 1, 1, 0, 0, 0, 0, -1, 1)'
+    expected = 'cftime.DatetimeGregorian(2000, 1, 1, 0, 0, 0, 0, 5, 1)'
+    # dayofwk, dayofyr are set
     assert repr(DatetimeGregorian(2000, 1, 1)) == expected
 
 



View it on GitLab: https://salsa.debian.org/debian-gis-team/cftime/compare/cd91fe8ccd4729dac0df3286fb7900e76b6081fa...02d0fba7406a685444b6f88c1adfeabbdff02a11

-- 
View it on GitLab: https://salsa.debian.org/debian-gis-team/cftime/compare/cd91fe8ccd4729dac0df3286fb7900e76b6081fa...02d0fba7406a685444b6f88c1adfeabbdff02a11
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/20181027/eb7f6bfc/attachment-0001.html>


More information about the Pkg-grass-devel mailing list