numpy 2.5.2__cp315-cp315-win32.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (942) hide show
  1. numpy/__config__.py +170 -0
  2. numpy/__config__.pyi +108 -0
  3. numpy/__init__.cython-30.pxd +1312 -0
  4. numpy/__init__.pxd +12 -0
  5. numpy/__init__.py +926 -0
  6. numpy/__init__.pyi +7691 -0
  7. numpy/_array_api_info.py +349 -0
  8. numpy/_array_api_info.pyi +177 -0
  9. numpy/_configtool.py +39 -0
  10. numpy/_configtool.pyi +1 -0
  11. numpy/_core/__init__.py +203 -0
  12. numpy/_core/__init__.pyi +666 -0
  13. numpy/_core/_add_newdocs.py +7131 -0
  14. numpy/_core/_add_newdocs.pyi +2 -0
  15. numpy/_core/_add_newdocs_scalars.py +381 -0
  16. numpy/_core/_add_newdocs_scalars.pyi +16 -0
  17. numpy/_core/_asarray.py +130 -0
  18. numpy/_core/_asarray.pyi +41 -0
  19. numpy/_core/_dtype.py +366 -0
  20. numpy/_core/_dtype.pyi +54 -0
  21. numpy/_core/_dtype_ctypes.py +120 -0
  22. numpy/_core/_dtype_ctypes.pyi +83 -0
  23. numpy/_core/_exceptions.py +162 -0
  24. numpy/_core/_exceptions.pyi +48 -0
  25. numpy/_core/_internal.py +964 -0
  26. numpy/_core/_internal.pyi +56 -0
  27. numpy/_core/_methods.py +252 -0
  28. numpy/_core/_methods.pyi +22 -0
  29. numpy/_core/_multiarray_tests.cp315-win32.lib +0 -0
  30. numpy/_core/_multiarray_tests.cp315-win32.pyd +0 -0
  31. numpy/_core/_multiarray_umath.cp315-win32.lib +0 -0
  32. numpy/_core/_multiarray_umath.cp315-win32.pyd +0 -0
  33. numpy/_core/_operand_flag_tests.cp315-win32.lib +0 -0
  34. numpy/_core/_operand_flag_tests.cp315-win32.pyd +0 -0
  35. numpy/_core/_rational_tests.cp315-win32.lib +0 -0
  36. numpy/_core/_rational_tests.cp315-win32.pyd +0 -0
  37. numpy/_core/_simd.cp315-win32.lib +0 -0
  38. numpy/_core/_simd.cp315-win32.pyd +0 -0
  39. numpy/_core/_simd.pyi +35 -0
  40. numpy/_core/_string_helpers.py +100 -0
  41. numpy/_core/_string_helpers.pyi +12 -0
  42. numpy/_core/_struct_ufunc_tests.cp315-win32.lib +0 -0
  43. numpy/_core/_struct_ufunc_tests.cp315-win32.pyd +0 -0
  44. numpy/_core/_type_aliases.py +130 -0
  45. numpy/_core/_type_aliases.pyi +86 -0
  46. numpy/_core/_ufunc_config.py +515 -0
  47. numpy/_core/_ufunc_config.pyi +67 -0
  48. numpy/_core/_umath_tests.cp315-win32.lib +0 -0
  49. numpy/_core/_umath_tests.cp315-win32.pyd +0 -0
  50. numpy/_core/_umath_tests.pyi +51 -0
  51. numpy/_core/arrayprint.py +1788 -0
  52. numpy/_core/arrayprint.pyi +152 -0
  53. numpy/_core/cversions.py +13 -0
  54. numpy/_core/defchararray.py +1429 -0
  55. numpy/_core/defchararray.pyi +778 -0
  56. numpy/_core/einsumfunc.py +1647 -0
  57. numpy/_core/einsumfunc.pyi +179 -0
  58. numpy/_core/fromnumeric.py +4271 -0
  59. numpy/_core/fromnumeric.pyi +3144 -0
  60. numpy/_core/function_base.py +547 -0
  61. numpy/_core/function_base.pyi +444 -0
  62. numpy/_core/getlimits.py +449 -0
  63. numpy/_core/getlimits.pyi +124 -0
  64. numpy/_core/include/numpy/__multiarray_api.c +386 -0
  65. numpy/_core/include/numpy/__multiarray_api.h +1708 -0
  66. numpy/_core/include/numpy/__ufunc_api.c +56 -0
  67. numpy/_core/include/numpy/__ufunc_api.h +357 -0
  68. numpy/_core/include/numpy/_neighborhood_iterator_imp.h +90 -0
  69. numpy/_core/include/numpy/_numpyconfig.h +33 -0
  70. numpy/_core/include/numpy/_public_dtype_api_table.h +86 -0
  71. numpy/_core/include/numpy/arrayobject.h +7 -0
  72. numpy/_core/include/numpy/arrayscalars.h +228 -0
  73. numpy/_core/include/numpy/dtype_api.h +557 -0
  74. numpy/_core/include/numpy/halffloat.h +70 -0
  75. numpy/_core/include/numpy/ndarrayobject.h +288 -0
  76. numpy/_core/include/numpy/ndarraytypes.h +2075 -0
  77. numpy/_core/include/numpy/npy_2_compat.h +430 -0
  78. numpy/_core/include/numpy/npy_2_complexcompat.h +28 -0
  79. numpy/_core/include/numpy/npy_3kcompat.h +374 -0
  80. numpy/_core/include/numpy/npy_common.h +989 -0
  81. numpy/_core/include/numpy/npy_cpu.h +126 -0
  82. numpy/_core/include/numpy/npy_endian.h +79 -0
  83. numpy/_core/include/numpy/npy_math.h +602 -0
  84. numpy/_core/include/numpy/npy_no_deprecated_api.h +20 -0
  85. numpy/_core/include/numpy/npy_os.h +42 -0
  86. numpy/_core/include/numpy/numpyconfig.h +187 -0
  87. numpy/_core/include/numpy/random/LICENSE.txt +21 -0
  88. numpy/_core/include/numpy/random/bitgen.h +20 -0
  89. numpy/_core/include/numpy/random/distributions.h +209 -0
  90. numpy/_core/include/numpy/random/libdivide.h +2079 -0
  91. numpy/_core/include/numpy/ufuncobject.h +368 -0
  92. numpy/_core/include/numpy/utils.h +99 -0
  93. numpy/_core/lib/npymath.lib +0 -0
  94. numpy/_core/lib/pkgconfig/numpy.pc +7 -0
  95. numpy/_core/memmap.py +362 -0
  96. numpy/_core/memmap.pyi +94 -0
  97. numpy/_core/multiarray.py +1743 -0
  98. numpy/_core/multiarray.pyi +1892 -0
  99. numpy/_core/numeric.py +2707 -0
  100. numpy/_core/numeric.pyi +1366 -0
  101. numpy/_core/numerictypes.py +576 -0
  102. numpy/_core/numerictypes.pyi +196 -0
  103. numpy/_core/overrides.py +188 -0
  104. numpy/_core/overrides.pyi +44 -0
  105. numpy/_core/printoptions.py +32 -0
  106. numpy/_core/printoptions.pyi +28 -0
  107. numpy/_core/records.py +1089 -0
  108. numpy/_core/records.pyi +336 -0
  109. numpy/_core/shape_base.py +996 -0
  110. numpy/_core/shape_base.pyi +210 -0
  111. numpy/_core/strings.py +1813 -0
  112. numpy/_core/strings.pyi +481 -0
  113. numpy/_core/tests/_locales.py +72 -0
  114. numpy/_core/tests/_natype.py +144 -0
  115. numpy/_core/tests/data/astype_copy.pkl +0 -0
  116. numpy/_core/tests/data/generate_umath_validation_data.cpp +170 -0
  117. numpy/_core/tests/data/recarray_from_file.fits +0 -0
  118. numpy/_core/tests/data/umath-validation-set-README.txt +15 -0
  119. numpy/_core/tests/data/umath-validation-set-arccos.csv +1429 -0
  120. numpy/_core/tests/data/umath-validation-set-arccosh.csv +1429 -0
  121. numpy/_core/tests/data/umath-validation-set-arcsin.csv +1429 -0
  122. numpy/_core/tests/data/umath-validation-set-arcsinh.csv +1429 -0
  123. numpy/_core/tests/data/umath-validation-set-arctan.csv +1429 -0
  124. numpy/_core/tests/data/umath-validation-set-arctanh.csv +1429 -0
  125. numpy/_core/tests/data/umath-validation-set-cbrt.csv +1429 -0
  126. numpy/_core/tests/data/umath-validation-set-cos.csv +1375 -0
  127. numpy/_core/tests/data/umath-validation-set-cosh.csv +1429 -0
  128. numpy/_core/tests/data/umath-validation-set-exp.csv +412 -0
  129. numpy/_core/tests/data/umath-validation-set-exp2.csv +1429 -0
  130. numpy/_core/tests/data/umath-validation-set-expm1.csv +1429 -0
  131. numpy/_core/tests/data/umath-validation-set-log.csv +271 -0
  132. numpy/_core/tests/data/umath-validation-set-log10.csv +1629 -0
  133. numpy/_core/tests/data/umath-validation-set-log1p.csv +1429 -0
  134. numpy/_core/tests/data/umath-validation-set-log2.csv +1629 -0
  135. numpy/_core/tests/data/umath-validation-set-sin.csv +1370 -0
  136. numpy/_core/tests/data/umath-validation-set-sinh.csv +1429 -0
  137. numpy/_core/tests/data/umath-validation-set-tan.csv +1429 -0
  138. numpy/_core/tests/data/umath-validation-set-tanh.csv +1429 -0
  139. numpy/_core/tests/examples/cython/checks.pyx +381 -0
  140. numpy/_core/tests/examples/cython/meson.build +52 -0
  141. numpy/_core/tests/examples/cython/setup.py +39 -0
  142. numpy/_core/tests/examples/limited_api/limited_api.c +455 -0
  143. numpy/_core/tests/examples/limited_api/limited_api_cython.pyx +155 -0
  144. numpy/_core/tests/examples/limited_api/meson.build +94 -0
  145. numpy/_core/tests/examples/limited_api/setup.py +24 -0
  146. numpy/_core/tests/test__exceptions.py +90 -0
  147. numpy/_core/tests/test_abc.py +54 -0
  148. numpy/_core/tests/test_api.py +668 -0
  149. numpy/_core/tests/test_argparse.py +90 -0
  150. numpy/_core/tests/test_array_api_info.py +113 -0
  151. numpy/_core/tests/test_array_coercion.py +943 -0
  152. numpy/_core/tests/test_array_interface.py +222 -0
  153. numpy/_core/tests/test_arraymethod.py +85 -0
  154. numpy/_core/tests/test_arrayobject.py +198 -0
  155. numpy/_core/tests/test_arrayprint.py +1363 -0
  156. numpy/_core/tests/test_casting_floatingpoint_errors.py +154 -0
  157. numpy/_core/tests/test_casting_unittests.py +970 -0
  158. numpy/_core/tests/test_conversion_utils.py +209 -0
  159. numpy/_core/tests/test_cpu_dispatcher.py +48 -0
  160. numpy/_core/tests/test_cpu_features.py +533 -0
  161. numpy/_core/tests/test_custom_dtypes.py +511 -0
  162. numpy/_core/tests/test_cython.py +377 -0
  163. numpy/_core/tests/test_datetime.py +3220 -0
  164. numpy/_core/tests/test_defchararray.py +879 -0
  165. numpy/_core/tests/test_deprecations.py +511 -0
  166. numpy/_core/tests/test_dlpack.py +262 -0
  167. numpy/_core/tests/test_dtype.py +2107 -0
  168. numpy/_core/tests/test_einsum.py +1368 -0
  169. numpy/_core/tests/test_errstate.py +131 -0
  170. numpy/_core/tests/test_extint128.py +217 -0
  171. numpy/_core/tests/test_finfo.py +86 -0
  172. numpy/_core/tests/test_function_base.py +502 -0
  173. numpy/_core/tests/test_getlimits.py +188 -0
  174. numpy/_core/tests/test_half.py +589 -0
  175. numpy/_core/tests/test_hashtable.py +156 -0
  176. numpy/_core/tests/test_indexerrors.py +122 -0
  177. numpy/_core/tests/test_indexing.py +1717 -0
  178. numpy/_core/tests/test_item_selection.py +178 -0
  179. numpy/_core/tests/test_limited_api.py +254 -0
  180. numpy/_core/tests/test_longdouble.py +370 -0
  181. numpy/_core/tests/test_mem_overlap.py +933 -0
  182. numpy/_core/tests/test_mem_policy.py +448 -0
  183. numpy/_core/tests/test_memmap.py +286 -0
  184. numpy/_core/tests/test_multiarray.py +11569 -0
  185. numpy/_core/tests/test_multiprocessing.py +55 -0
  186. numpy/_core/tests/test_multithreading.py +746 -0
  187. numpy/_core/tests/test_nditer.py +3690 -0
  188. numpy/_core/tests/test_nep50_promotions.py +287 -0
  189. numpy/_core/tests/test_numeric.py +4278 -0
  190. numpy/_core/tests/test_numerictypes.py +640 -0
  191. numpy/_core/tests/test_overrides.py +800 -0
  192. numpy/_core/tests/test_print.py +202 -0
  193. numpy/_core/tests/test_protocols.py +46 -0
  194. numpy/_core/tests/test_records.py +595 -0
  195. numpy/_core/tests/test_regression.py +2672 -0
  196. numpy/_core/tests/test_scalar_ctors.py +203 -0
  197. numpy/_core/tests/test_scalar_methods.py +327 -0
  198. numpy/_core/tests/test_scalarbuffer.py +154 -0
  199. numpy/_core/tests/test_scalarinherit.py +105 -0
  200. numpy/_core/tests/test_scalarmath.py +1167 -0
  201. numpy/_core/tests/test_scalarprint.py +403 -0
  202. numpy/_core/tests/test_shape_base.py +899 -0
  203. numpy/_core/tests/test_simd.py +1345 -0
  204. numpy/_core/tests/test_simd_module.py +105 -0
  205. numpy/_core/tests/test_stringdtype.py +2573 -0
  206. numpy/_core/tests/test_strings.py +1506 -0
  207. numpy/_core/tests/test_ufunc.py +3452 -0
  208. numpy/_core/tests/test_umath.py +5231 -0
  209. numpy/_core/tests/test_umath_accuracy.py +92 -0
  210. numpy/_core/tests/test_umath_complex.py +631 -0
  211. numpy/_core/tests/test_unicode.py +369 -0
  212. numpy/_core/umath.py +59 -0
  213. numpy/_core/umath.pyi +232 -0
  214. numpy/_distributor_init.py +15 -0
  215. numpy/_distributor_init.pyi +1 -0
  216. numpy/_expired_attrs_2_0.py +78 -0
  217. numpy/_expired_attrs_2_0.pyi +61 -0
  218. numpy/_globals.py +121 -0
  219. numpy/_globals.pyi +17 -0
  220. numpy/_pyinstaller/__init__.py +0 -0
  221. numpy/_pyinstaller/__init__.pyi +0 -0
  222. numpy/_pyinstaller/hook-numpy.py +35 -0
  223. numpy/_pyinstaller/hook-numpy.pyi +6 -0
  224. numpy/_pyinstaller/tests/__init__.py +16 -0
  225. numpy/_pyinstaller/tests/pyinstaller-smoke.py +32 -0
  226. numpy/_pyinstaller/tests/test_pyinstaller.py +35 -0
  227. numpy/_pytesttester.py +186 -0
  228. numpy/_pytesttester.pyi +18 -0
  229. numpy/_typing/__init__.py +147 -0
  230. numpy/_typing/_add_docstring.py +153 -0
  231. numpy/_typing/_array_like.py +92 -0
  232. numpy/_typing/_char_codes.py +156 -0
  233. numpy/_typing/_dtype_like.py +108 -0
  234. numpy/_typing/_extended_precision.py +15 -0
  235. numpy/_typing/_nbit.py +17 -0
  236. numpy/_typing/_nbit_base.py +93 -0
  237. numpy/_typing/_nbit_base.pyi +39 -0
  238. numpy/_typing/_nested_sequence.py +85 -0
  239. numpy/_typing/_scalars.py +20 -0
  240. numpy/_typing/_shape.py +8 -0
  241. numpy/_typing/_ufunc.py +7 -0
  242. numpy/_typing/_ufunc.pyi +970 -0
  243. numpy/_utils/__init__.py +95 -0
  244. numpy/_utils/__init__.pyi +25 -0
  245. numpy/_utils/_conversions.py +18 -0
  246. numpy/_utils/_conversions.pyi +4 -0
  247. numpy/_utils/_inspect.py +192 -0
  248. numpy/_utils/_inspect.pyi +67 -0
  249. numpy/_utils/_pep440.py +486 -0
  250. numpy/_utils/_pep440.pyi +121 -0
  251. numpy/char/__init__.py +31 -0
  252. numpy/char/__init__.pyi +111 -0
  253. numpy/conftest.py +249 -0
  254. numpy/core/__init__.py +33 -0
  255. numpy/core/__init__.pyi +45 -0
  256. numpy/core/_dtype.py +10 -0
  257. numpy/core/_dtype.pyi +0 -0
  258. numpy/core/_dtype_ctypes.py +10 -0
  259. numpy/core/_dtype_ctypes.pyi +0 -0
  260. numpy/core/_internal.py +27 -0
  261. numpy/core/_internal.pyi +1 -0
  262. numpy/core/_multiarray_umath.py +57 -0
  263. numpy/core/_utils.py +21 -0
  264. numpy/core/arrayprint.py +10 -0
  265. numpy/core/arrayprint.pyi +4 -0
  266. numpy/core/defchararray.py +10 -0
  267. numpy/core/defchararray.pyi +4 -0
  268. numpy/core/einsumfunc.py +10 -0
  269. numpy/core/einsumfunc.pyi +4 -0
  270. numpy/core/fromnumeric.py +10 -0
  271. numpy/core/fromnumeric.pyi +4 -0
  272. numpy/core/function_base.py +10 -0
  273. numpy/core/function_base.pyi +4 -0
  274. numpy/core/getlimits.py +10 -0
  275. numpy/core/getlimits.pyi +4 -0
  276. numpy/core/multiarray.py +25 -0
  277. numpy/core/multiarray.pyi +4 -0
  278. numpy/core/numeric.py +12 -0
  279. numpy/core/numeric.pyi +4 -0
  280. numpy/core/numerictypes.py +10 -0
  281. numpy/core/numerictypes.pyi +4 -0
  282. numpy/core/overrides.py +10 -0
  283. numpy/core/overrides.pyi +7 -0
  284. numpy/core/records.py +10 -0
  285. numpy/core/records.pyi +4 -0
  286. numpy/core/shape_base.py +10 -0
  287. numpy/core/shape_base.pyi +4 -0
  288. numpy/core/umath.py +10 -0
  289. numpy/core/umath.pyi +4 -0
  290. numpy/ctypeslib/__init__.py +13 -0
  291. numpy/ctypeslib/__init__.pyi +15 -0
  292. numpy/ctypeslib/_ctypeslib.py +603 -0
  293. numpy/ctypeslib/_ctypeslib.pyi +222 -0
  294. numpy/doc/ufuncs.py +138 -0
  295. numpy/dtypes.py +86 -0
  296. numpy/dtypes.pyi +627 -0
  297. numpy/exceptions.py +246 -0
  298. numpy/exceptions.pyi +27 -0
  299. numpy/f2py/__init__.py +80 -0
  300. numpy/f2py/__init__.pyi +5 -0
  301. numpy/f2py/__main__.py +5 -0
  302. numpy/f2py/__version__.py +1 -0
  303. numpy/f2py/__version__.pyi +1 -0
  304. numpy/f2py/_backends/__init__.py +6 -0
  305. numpy/f2py/_backends/__init__.pyi +5 -0
  306. numpy/f2py/_backends/_backend.py +44 -0
  307. numpy/f2py/_backends/_backend.pyi +46 -0
  308. numpy/f2py/_backends/_meson.py +244 -0
  309. numpy/f2py/_backends/_meson.pyi +61 -0
  310. numpy/f2py/_backends/meson.build.template +63 -0
  311. numpy/f2py/_isocbind.py +62 -0
  312. numpy/f2py/_isocbind.pyi +13 -0
  313. numpy/f2py/_src_pyf.py +247 -0
  314. numpy/f2py/_src_pyf.pyi +28 -0
  315. numpy/f2py/auxfuncs.py +1005 -0
  316. numpy/f2py/auxfuncs.pyi +259 -0
  317. numpy/f2py/capi_maps.py +811 -0
  318. numpy/f2py/capi_maps.pyi +33 -0
  319. numpy/f2py/cb_rules.py +649 -0
  320. numpy/f2py/cb_rules.pyi +17 -0
  321. numpy/f2py/cfuncs.py +1579 -0
  322. numpy/f2py/cfuncs.pyi +31 -0
  323. numpy/f2py/common_rules.py +145 -0
  324. numpy/f2py/common_rules.pyi +9 -0
  325. numpy/f2py/crackfortran.py +3727 -0
  326. numpy/f2py/crackfortran.pyi +254 -0
  327. numpy/f2py/diagnose.py +57 -0
  328. numpy/f2py/diagnose.pyi +1 -0
  329. numpy/f2py/f2py2e.py +755 -0
  330. numpy/f2py/f2py2e.pyi +69 -0
  331. numpy/f2py/f90mod_rules.py +281 -0
  332. numpy/f2py/f90mod_rules.pyi +16 -0
  333. numpy/f2py/func2subr.py +329 -0
  334. numpy/f2py/func2subr.pyi +7 -0
  335. numpy/f2py/rules.py +1641 -0
  336. numpy/f2py/rules.pyi +36 -0
  337. numpy/f2py/setup.cfg +3 -0
  338. numpy/f2py/src/fortranobject.c +1471 -0
  339. numpy/f2py/src/fortranobject.h +173 -0
  340. numpy/f2py/symbolic.py +1518 -0
  341. numpy/f2py/symbolic.pyi +220 -0
  342. numpy/f2py/tests/__init__.py +16 -0
  343. numpy/f2py/tests/src/abstract_interface/foo.f90 +34 -0
  344. numpy/f2py/tests/src/abstract_interface/gh18403_mod.f90 +6 -0
  345. numpy/f2py/tests/src/array_from_pyobj/wrapmodule.c +262 -0
  346. numpy/f2py/tests/src/assumed_shape/.f2py_f2cmap +1 -0
  347. numpy/f2py/tests/src/assumed_shape/foo_free.f90 +34 -0
  348. numpy/f2py/tests/src/assumed_shape/foo_mod.f90 +41 -0
  349. numpy/f2py/tests/src/assumed_shape/foo_use.f90 +19 -0
  350. numpy/f2py/tests/src/assumed_shape/precision.f90 +4 -0
  351. numpy/f2py/tests/src/block_docstring/foo.f +6 -0
  352. numpy/f2py/tests/src/callback/foo.f +62 -0
  353. numpy/f2py/tests/src/callback/gh17797.f90 +7 -0
  354. numpy/f2py/tests/src/callback/gh18335.f90 +17 -0
  355. numpy/f2py/tests/src/callback/gh25211.f +10 -0
  356. numpy/f2py/tests/src/callback/gh25211.pyf +18 -0
  357. numpy/f2py/tests/src/callback/gh26681.f90 +18 -0
  358. numpy/f2py/tests/src/cli/gh_22819.pyf +6 -0
  359. numpy/f2py/tests/src/cli/hi77.f +3 -0
  360. numpy/f2py/tests/src/cli/hiworld.f90 +3 -0
  361. numpy/f2py/tests/src/common/block.f +11 -0
  362. numpy/f2py/tests/src/common/gh19161.f90 +10 -0
  363. numpy/f2py/tests/src/crackfortran/accesstype.f90 +13 -0
  364. numpy/f2py/tests/src/crackfortran/common_with_division.f +17 -0
  365. numpy/f2py/tests/src/crackfortran/data_common.f +8 -0
  366. numpy/f2py/tests/src/crackfortran/data_multiplier.f +5 -0
  367. numpy/f2py/tests/src/crackfortran/data_stmts.f90 +20 -0
  368. numpy/f2py/tests/src/crackfortran/data_with_comments.f +8 -0
  369. numpy/f2py/tests/src/crackfortran/foo_deps.f90 +6 -0
  370. numpy/f2py/tests/src/crackfortran/gh15035.f +16 -0
  371. numpy/f2py/tests/src/crackfortran/gh17859.f +12 -0
  372. numpy/f2py/tests/src/crackfortran/gh22648.pyf +7 -0
  373. numpy/f2py/tests/src/crackfortran/gh23533.f +5 -0
  374. numpy/f2py/tests/src/crackfortran/gh23598.f90 +4 -0
  375. numpy/f2py/tests/src/crackfortran/gh23598Warn.f90 +11 -0
  376. numpy/f2py/tests/src/crackfortran/gh23879.f90 +20 -0
  377. numpy/f2py/tests/src/crackfortran/gh27697.f90 +12 -0
  378. numpy/f2py/tests/src/crackfortran/gh2848.f90 +13 -0
  379. numpy/f2py/tests/src/crackfortran/operators.f90 +49 -0
  380. numpy/f2py/tests/src/crackfortran/privatemod.f90 +11 -0
  381. numpy/f2py/tests/src/crackfortran/publicmod.f90 +10 -0
  382. numpy/f2py/tests/src/crackfortran/pubprivmod.f90 +10 -0
  383. numpy/f2py/tests/src/crackfortran/unicode_comment.f90 +4 -0
  384. numpy/f2py/tests/src/f2cmap/.f2py_f2cmap +1 -0
  385. numpy/f2py/tests/src/f2cmap/isoFortranEnvMap.f90 +9 -0
  386. numpy/f2py/tests/src/inplace/foo.f +31 -0
  387. numpy/f2py/tests/src/isocintrin/isoCtests.f90 +34 -0
  388. numpy/f2py/tests/src/kind/foo.f90 +20 -0
  389. numpy/f2py/tests/src/mixed/foo.f +5 -0
  390. numpy/f2py/tests/src/mixed/foo_fixed.f90 +8 -0
  391. numpy/f2py/tests/src/mixed/foo_free.f90 +8 -0
  392. numpy/f2py/tests/src/modules/gh25337/data.f90 +8 -0
  393. numpy/f2py/tests/src/modules/gh25337/use_data.f90 +6 -0
  394. numpy/f2py/tests/src/modules/gh26920/two_mods_with_no_public_entities.f90 +21 -0
  395. numpy/f2py/tests/src/modules/gh26920/two_mods_with_one_public_routine.f90 +21 -0
  396. numpy/f2py/tests/src/modules/module_data_docstring.f90 +12 -0
  397. numpy/f2py/tests/src/modules/use_modules.f90 +20 -0
  398. numpy/f2py/tests/src/negative_bounds/issue_20853.f90 +7 -0
  399. numpy/f2py/tests/src/parameter/constant_array.f90 +45 -0
  400. numpy/f2py/tests/src/parameter/constant_both.f90 +57 -0
  401. numpy/f2py/tests/src/parameter/constant_compound.f90 +15 -0
  402. numpy/f2py/tests/src/parameter/constant_integer.f90 +22 -0
  403. numpy/f2py/tests/src/parameter/constant_non_compound.f90 +23 -0
  404. numpy/f2py/tests/src/parameter/constant_real.f90 +23 -0
  405. numpy/f2py/tests/src/quoted_character/foo.f +14 -0
  406. numpy/f2py/tests/src/regression/AB.inc +1 -0
  407. numpy/f2py/tests/src/regression/assignOnlyModule.f90 +25 -0
  408. numpy/f2py/tests/src/regression/complex_struct_compat.f90 +8 -0
  409. numpy/f2py/tests/src/regression/complex_struct_compat.pyf +12 -0
  410. numpy/f2py/tests/src/regression/datonly.f90 +17 -0
  411. numpy/f2py/tests/src/regression/f77comments.f +26 -0
  412. numpy/f2py/tests/src/regression/f77fixedform.f95 +5 -0
  413. numpy/f2py/tests/src/regression/f90continuation.f90 +9 -0
  414. numpy/f2py/tests/src/regression/incfile.f90 +5 -0
  415. numpy/f2py/tests/src/regression/inout.f90 +9 -0
  416. numpy/f2py/tests/src/regression/lower_f2py_fortran.f90 +5 -0
  417. numpy/f2py/tests/src/regression/mod_derived_types.f90 +23 -0
  418. numpy/f2py/tests/src/return_character/foo77.f +45 -0
  419. numpy/f2py/tests/src/return_character/foo90.f90 +48 -0
  420. numpy/f2py/tests/src/return_complex/foo77.f +45 -0
  421. numpy/f2py/tests/src/return_complex/foo90.f90 +48 -0
  422. numpy/f2py/tests/src/return_integer/foo77.f +56 -0
  423. numpy/f2py/tests/src/return_integer/foo90.f90 +59 -0
  424. numpy/f2py/tests/src/return_logical/foo77.f +56 -0
  425. numpy/f2py/tests/src/return_logical/foo90.f90 +59 -0
  426. numpy/f2py/tests/src/return_real/foo77.f +45 -0
  427. numpy/f2py/tests/src/return_real/foo90.f90 +48 -0
  428. numpy/f2py/tests/src/routines/funcfortranname.f +5 -0
  429. numpy/f2py/tests/src/routines/funcfortranname.pyf +11 -0
  430. numpy/f2py/tests/src/routines/subrout.f +4 -0
  431. numpy/f2py/tests/src/routines/subrout.pyf +10 -0
  432. numpy/f2py/tests/src/size/foo.f90 +44 -0
  433. numpy/f2py/tests/src/string/char.f90 +29 -0
  434. numpy/f2py/tests/src/string/fixed_string.f90 +34 -0
  435. numpy/f2py/tests/src/string/gh24008.f +8 -0
  436. numpy/f2py/tests/src/string/gh24662.f90 +7 -0
  437. numpy/f2py/tests/src/string/gh25286.f90 +14 -0
  438. numpy/f2py/tests/src/string/gh25286.pyf +12 -0
  439. numpy/f2py/tests/src/string/gh25286_bc.pyf +12 -0
  440. numpy/f2py/tests/src/string/scalar_string.f90 +9 -0
  441. numpy/f2py/tests/src/string/string.f +12 -0
  442. numpy/f2py/tests/src/value_attrspec/gh21665.f90 +9 -0
  443. numpy/f2py/tests/test_abstract_interface.py +26 -0
  444. numpy/f2py/tests/test_array_from_pyobj.py +732 -0
  445. numpy/f2py/tests/test_assumed_shape.py +52 -0
  446. numpy/f2py/tests/test_block_docstring.py +16 -0
  447. numpy/f2py/tests/test_callback.py +262 -0
  448. numpy/f2py/tests/test_capi_maps.py +10 -0
  449. numpy/f2py/tests/test_character.py +644 -0
  450. numpy/f2py/tests/test_common.py +24 -0
  451. numpy/f2py/tests/test_crackfortran.py +427 -0
  452. numpy/f2py/tests/test_data.py +74 -0
  453. numpy/f2py/tests/test_docs.py +66 -0
  454. numpy/f2py/tests/test_f2cmap.py +20 -0
  455. numpy/f2py/tests/test_f2py2e.py +1006 -0
  456. numpy/f2py/tests/test_inplace.py +49 -0
  457. numpy/f2py/tests/test_isoc.py +56 -0
  458. numpy/f2py/tests/test_kind.py +53 -0
  459. numpy/f2py/tests/test_mixed.py +31 -0
  460. numpy/f2py/tests/test_modules.py +87 -0
  461. numpy/f2py/tests/test_parameter.py +121 -0
  462. numpy/f2py/tests/test_pyf_src.py +43 -0
  463. numpy/f2py/tests/test_quoted_character.py +19 -0
  464. numpy/f2py/tests/test_regression.py +202 -0
  465. numpy/f2py/tests/test_return_character.py +48 -0
  466. numpy/f2py/tests/test_return_complex.py +67 -0
  467. numpy/f2py/tests/test_return_integer.py +55 -0
  468. numpy/f2py/tests/test_return_logical.py +66 -0
  469. numpy/f2py/tests/test_return_real.py +109 -0
  470. numpy/f2py/tests/test_routines.py +29 -0
  471. numpy/f2py/tests/test_semicolon_split.py +76 -0
  472. numpy/f2py/tests/test_size.py +42 -0
  473. numpy/f2py/tests/test_string.py +102 -0
  474. numpy/f2py/tests/test_symbolic.py +501 -0
  475. numpy/f2py/tests/test_value_attrspec.py +15 -0
  476. numpy/f2py/tests/util.py +442 -0
  477. numpy/f2py/use_rules.py +100 -0
  478. numpy/f2py/use_rules.pyi +9 -0
  479. numpy/fft/__init__.py +213 -0
  480. numpy/fft/__init__.pyi +38 -0
  481. numpy/fft/_helper.py +235 -0
  482. numpy/fft/_helper.pyi +145 -0
  483. numpy/fft/_pocketfft.py +1693 -0
  484. numpy/fft/_pocketfft.pyi +1131 -0
  485. numpy/fft/_pocketfft_umath.cp315-win32.lib +0 -0
  486. numpy/fft/_pocketfft_umath.cp315-win32.pyd +0 -0
  487. numpy/fft/tests/__init__.py +0 -0
  488. numpy/fft/tests/test_helper.py +167 -0
  489. numpy/fft/tests/test_pocketfft.py +609 -0
  490. numpy/lib/__init__.py +90 -0
  491. numpy/lib/__init__.pyi +52 -0
  492. numpy/lib/_array_utils_impl.py +62 -0
  493. numpy/lib/_array_utils_impl.pyi +10 -0
  494. numpy/lib/_arraypad_impl.py +926 -0
  495. numpy/lib/_arraypad_impl.pyi +99 -0
  496. numpy/lib/_arraysetops_impl.py +1158 -0
  497. numpy/lib/_arraysetops_impl.pyi +460 -0
  498. numpy/lib/_arrayterator_impl.py +224 -0
  499. numpy/lib/_arrayterator_impl.pyi +45 -0
  500. numpy/lib/_datasource.py +700 -0
  501. numpy/lib/_datasource.pyi +30 -0
  502. numpy/lib/_format_impl.py +1038 -0
  503. numpy/lib/_format_impl.pyi +56 -0
  504. numpy/lib/_function_base_impl.py +5775 -0
  505. numpy/lib/_function_base_impl.pyi +2315 -0
  506. numpy/lib/_histograms_impl.py +1085 -0
  507. numpy/lib/_histograms_impl.pyi +273 -0
  508. numpy/lib/_index_tricks_impl.py +1048 -0
  509. numpy/lib/_index_tricks_impl.pyi +350 -0
  510. numpy/lib/_iotools.py +900 -0
  511. numpy/lib/_iotools.pyi +113 -0
  512. numpy/lib/_nanfunctions_impl.py +2006 -0
  513. numpy/lib/_nanfunctions_impl.pyi +48 -0
  514. numpy/lib/_npyio_impl.py +2491 -0
  515. numpy/lib/_npyio_impl.pyi +288 -0
  516. numpy/lib/_polynomial_impl.py +1467 -0
  517. numpy/lib/_polynomial_impl.pyi +435 -0
  518. numpy/lib/_scimath_impl.py +642 -0
  519. numpy/lib/_scimath_impl.pyi +93 -0
  520. numpy/lib/_shape_base_impl.py +1247 -0
  521. numpy/lib/_shape_base_impl.pyi +256 -0
  522. numpy/lib/_stride_tricks_impl.py +656 -0
  523. numpy/lib/_stride_tricks_impl.pyi +75 -0
  524. numpy/lib/_twodim_base_impl.py +1242 -0
  525. numpy/lib/_twodim_base_impl.pyi +397 -0
  526. numpy/lib/_type_check_impl.py +714 -0
  527. numpy/lib/_type_check_impl.pyi +450 -0
  528. numpy/lib/_ufunclike_impl.py +212 -0
  529. numpy/lib/_ufunclike_impl.pyi +41 -0
  530. numpy/lib/_user_array_impl.py +310 -0
  531. numpy/lib/_user_array_impl.pyi +229 -0
  532. numpy/lib/_utils_impl.py +541 -0
  533. numpy/lib/_utils_impl.pyi +18 -0
  534. numpy/lib/_version.py +153 -0
  535. numpy/lib/_version.pyi +22 -0
  536. numpy/lib/array_utils.py +7 -0
  537. numpy/lib/array_utils.pyi +6 -0
  538. numpy/lib/format.py +24 -0
  539. numpy/lib/format.pyi +24 -0
  540. numpy/lib/introspect.py +94 -0
  541. numpy/lib/introspect.pyi +3 -0
  542. numpy/lib/mixins.py +180 -0
  543. numpy/lib/mixins.pyi +78 -0
  544. numpy/lib/npyio.py +1 -0
  545. numpy/lib/npyio.pyi +5 -0
  546. numpy/lib/recfunctions.py +1681 -0
  547. numpy/lib/recfunctions.pyi +436 -0
  548. numpy/lib/scimath.py +13 -0
  549. numpy/lib/scimath.pyi +12 -0
  550. numpy/lib/stride_tricks.py +1 -0
  551. numpy/lib/stride_tricks.pyi +4 -0
  552. numpy/lib/tests/__init__.py +0 -0
  553. numpy/lib/tests/data/py2-np0-objarr.npy +0 -0
  554. numpy/lib/tests/data/py2-objarr.npy +0 -0
  555. numpy/lib/tests/data/py2-objarr.npz +0 -0
  556. numpy/lib/tests/data/py3-objarr.npy +0 -0
  557. numpy/lib/tests/data/py3-objarr.npz +0 -0
  558. numpy/lib/tests/data/python3.npy +0 -0
  559. numpy/lib/tests/data/win64python2.npy +0 -0
  560. numpy/lib/tests/test__datasource.py +328 -0
  561. numpy/lib/tests/test__iotools.py +358 -0
  562. numpy/lib/tests/test__version.py +64 -0
  563. numpy/lib/tests/test_array_utils.py +32 -0
  564. numpy/lib/tests/test_arraypad.py +1427 -0
  565. numpy/lib/tests/test_arraysetops.py +1304 -0
  566. numpy/lib/tests/test_arrayterator.py +45 -0
  567. numpy/lib/tests/test_format.py +1043 -0
  568. numpy/lib/tests/test_function_base.py +4787 -0
  569. numpy/lib/tests/test_histograms.py +855 -0
  570. numpy/lib/tests/test_index_tricks.py +703 -0
  571. numpy/lib/tests/test_io.py +2733 -0
  572. numpy/lib/tests/test_loadtxt.py +1077 -0
  573. numpy/lib/tests/test_mixins.py +215 -0
  574. numpy/lib/tests/test_nanfunctions.py +1449 -0
  575. numpy/lib/tests/test_packbits.py +374 -0
  576. numpy/lib/tests/test_polynomial.py +333 -0
  577. numpy/lib/tests/test_recfunctions.py +1042 -0
  578. numpy/lib/tests/test_regression.py +231 -0
  579. numpy/lib/tests/test_shape_base.py +813 -0
  580. numpy/lib/tests/test_stride_tricks.py +890 -0
  581. numpy/lib/tests/test_twodim_base.py +564 -0
  582. numpy/lib/tests/test_type_check.py +473 -0
  583. numpy/lib/tests/test_ufunclike.py +121 -0
  584. numpy/lib/tests/test_utils.py +80 -0
  585. numpy/lib/user_array.py +1 -0
  586. numpy/lib/user_array.pyi +1 -0
  587. numpy/linalg/__init__.py +95 -0
  588. numpy/linalg/__init__.pyi +71 -0
  589. numpy/linalg/_linalg.py +3649 -0
  590. numpy/linalg/_linalg.pyi +1230 -0
  591. numpy/linalg/_umath_linalg.cp315-win32.lib +0 -0
  592. numpy/linalg/_umath_linalg.cp315-win32.pyd +0 -0
  593. numpy/linalg/_umath_linalg.pyi +60 -0
  594. numpy/linalg/lapack_lite.cp315-win32.lib +0 -0
  595. numpy/linalg/lapack_lite.cp315-win32.pyd +0 -0
  596. numpy/linalg/lapack_lite.pyi +143 -0
  597. numpy/linalg/tests/__init__.py +0 -0
  598. numpy/linalg/tests/test_deprecations.py +21 -0
  599. numpy/linalg/tests/test_linalg.py +2492 -0
  600. numpy/linalg/tests/test_regression.py +191 -0
  601. numpy/ma/API_CHANGES.txt +135 -0
  602. numpy/ma/LICENSE +24 -0
  603. numpy/ma/README.rst +236 -0
  604. numpy/ma/__init__.py +53 -0
  605. numpy/ma/__init__.pyi +458 -0
  606. numpy/ma/core.py +9000 -0
  607. numpy/ma/core.pyi +4767 -0
  608. numpy/ma/extras.py +2266 -0
  609. numpy/ma/extras.pyi +770 -0
  610. numpy/ma/mrecords.py +739 -0
  611. numpy/ma/mrecords.pyi +313 -0
  612. numpy/ma/tests/__init__.py +0 -0
  613. numpy/ma/tests/test_arrayobject.py +40 -0
  614. numpy/ma/tests/test_core.py +6112 -0
  615. numpy/ma/tests/test_deprecations.py +73 -0
  616. numpy/ma/tests/test_extras.py +1945 -0
  617. numpy/ma/tests/test_mrecords.py +495 -0
  618. numpy/ma/tests/test_old_ma.py +939 -0
  619. numpy/ma/tests/test_regression.py +83 -0
  620. numpy/ma/tests/test_subclassing.py +469 -0
  621. numpy/ma/testutils.py +294 -0
  622. numpy/ma/testutils.pyi +69 -0
  623. numpy/matlib.py +380 -0
  624. numpy/matlib.pyi +580 -0
  625. numpy/matrixlib/__init__.py +12 -0
  626. numpy/matrixlib/__init__.pyi +3 -0
  627. numpy/matrixlib/defmatrix.py +1117 -0
  628. numpy/matrixlib/defmatrix.pyi +211 -0
  629. numpy/matrixlib/tests/__init__.py +0 -0
  630. numpy/matrixlib/tests/test_defmatrix.py +475 -0
  631. numpy/matrixlib/tests/test_interaction.py +360 -0
  632. numpy/matrixlib/tests/test_masked_matrix.py +240 -0
  633. numpy/matrixlib/tests/test_matrix_linalg.py +110 -0
  634. numpy/matrixlib/tests/test_multiarray.py +17 -0
  635. numpy/matrixlib/tests/test_numeric.py +18 -0
  636. numpy/matrixlib/tests/test_regression.py +31 -0
  637. numpy/polynomial/__init__.py +187 -0
  638. numpy/polynomial/__init__.pyi +31 -0
  639. numpy/polynomial/_polybase.py +1191 -0
  640. numpy/polynomial/_polybase.pyi +255 -0
  641. numpy/polynomial/_polytypes.pyi +536 -0
  642. numpy/polynomial/chebyshev.py +2053 -0
  643. numpy/polynomial/chebyshev.pyi +173 -0
  644. numpy/polynomial/hermite.py +1794 -0
  645. numpy/polynomial/hermite.pyi +110 -0
  646. numpy/polynomial/hermite_e.py +1692 -0
  647. numpy/polynomial/hermite_e.pyi +110 -0
  648. numpy/polynomial/laguerre.py +1729 -0
  649. numpy/polynomial/laguerre.pyi +103 -0
  650. numpy/polynomial/legendre.py +1655 -0
  651. numpy/polynomial/legendre.pyi +103 -0
  652. numpy/polynomial/polynomial.py +1683 -0
  653. numpy/polynomial/polynomial.pyi +112 -0
  654. numpy/polynomial/polyutils.py +759 -0
  655. numpy/polynomial/polyutils.pyi +295 -0
  656. numpy/polynomial/tests/__init__.py +0 -0
  657. numpy/polynomial/tests/test_chebyshev.py +639 -0
  658. numpy/polynomial/tests/test_classes.py +625 -0
  659. numpy/polynomial/tests/test_hermite.py +574 -0
  660. numpy/polynomial/tests/test_hermite_e.py +575 -0
  661. numpy/polynomial/tests/test_laguerre.py +556 -0
  662. numpy/polynomial/tests/test_legendre.py +587 -0
  663. numpy/polynomial/tests/test_polynomial.py +713 -0
  664. numpy/polynomial/tests/test_polyutils.py +123 -0
  665. numpy/polynomial/tests/test_printing.py +562 -0
  666. numpy/polynomial/tests/test_symbol.py +217 -0
  667. numpy/py.typed +0 -0
  668. numpy/random/LICENSE.md +71 -0
  669. numpy/random/__init__.pxd +14 -0
  670. numpy/random/__init__.py +213 -0
  671. numpy/random/__init__.pyi +124 -0
  672. numpy/random/_bounded_integers.cp315-win32.lib +0 -0
  673. numpy/random/_bounded_integers.cp315-win32.pyd +0 -0
  674. numpy/random/_bounded_integers.pxd +38 -0
  675. numpy/random/_bounded_integers.pyi +1 -0
  676. numpy/random/_common.cp315-win32.lib +0 -0
  677. numpy/random/_common.cp315-win32.pyd +0 -0
  678. numpy/random/_common.pxd +110 -0
  679. numpy/random/_common.pyi +17 -0
  680. numpy/random/_examples/cffi/extending.py +44 -0
  681. numpy/random/_examples/cffi/parse.py +53 -0
  682. numpy/random/_examples/cython/extending.pyx +77 -0
  683. numpy/random/_examples/cython/extending_distributions.pyx +117 -0
  684. numpy/random/_examples/cython/meson.build +53 -0
  685. numpy/random/_examples/numba/extending.py +86 -0
  686. numpy/random/_examples/numba/extending_distributions.py +67 -0
  687. numpy/random/_generator.cp315-win32.lib +0 -0
  688. numpy/random/_generator.cp315-win32.pyd +0 -0
  689. numpy/random/_generator.pyi +769 -0
  690. numpy/random/_mt19937.cp315-win32.lib +0 -0
  691. numpy/random/_mt19937.cp315-win32.pyd +0 -0
  692. numpy/random/_mt19937.pyi +27 -0
  693. numpy/random/_pcg64.cp315-win32.lib +0 -0
  694. numpy/random/_pcg64.cp315-win32.pyd +0 -0
  695. numpy/random/_pcg64.pyi +36 -0
  696. numpy/random/_philox.cp315-win32.lib +0 -0
  697. numpy/random/_philox.cp315-win32.pyd +0 -0
  698. numpy/random/_philox.pyi +36 -0
  699. numpy/random/_pickle.py +88 -0
  700. numpy/random/_pickle.pyi +43 -0
  701. numpy/random/_sfc64.cp315-win32.lib +0 -0
  702. numpy/random/_sfc64.cp315-win32.pyd +0 -0
  703. numpy/random/_sfc64.pyi +25 -0
  704. numpy/random/bit_generator.cp315-win32.lib +0 -0
  705. numpy/random/bit_generator.cp315-win32.pyd +0 -0
  706. numpy/random/bit_generator.pxd +35 -0
  707. numpy/random/bit_generator.pyi +122 -0
  708. numpy/random/c_distributions.pxd +119 -0
  709. numpy/random/lib/npyrandom.lib +0 -0
  710. numpy/random/mtrand.cp315-win32.lib +0 -0
  711. numpy/random/mtrand.cp315-win32.pyd +0 -0
  712. numpy/random/mtrand.pyi +996 -0
  713. numpy/random/tests/__init__.py +0 -0
  714. numpy/random/tests/data/__init__.py +0 -0
  715. numpy/random/tests/data/generator_pcg64_np121.pkl.gz +0 -0
  716. numpy/random/tests/data/generator_pcg64_np126.pkl.gz +0 -0
  717. numpy/random/tests/data/mt19937-testset-1.csv +1001 -0
  718. numpy/random/tests/data/mt19937-testset-2.csv +1001 -0
  719. numpy/random/tests/data/pcg64-testset-1.csv +1001 -0
  720. numpy/random/tests/data/pcg64-testset-2.csv +1001 -0
  721. numpy/random/tests/data/pcg64dxsm-testset-1.csv +1001 -0
  722. numpy/random/tests/data/pcg64dxsm-testset-2.csv +1001 -0
  723. numpy/random/tests/data/philox-testset-1.csv +1001 -0
  724. numpy/random/tests/data/philox-testset-2.csv +1001 -0
  725. numpy/random/tests/data/sfc64-testset-1.csv +1001 -0
  726. numpy/random/tests/data/sfc64-testset-2.csv +1001 -0
  727. numpy/random/tests/data/sfc64_np126.pkl.gz +0 -0
  728. numpy/random/tests/test_direct.py +620 -0
  729. numpy/random/tests/test_extending.py +129 -0
  730. numpy/random/tests/test_generator_mt19937.py +2830 -0
  731. numpy/random/tests/test_generator_mt19937_regressions.py +240 -0
  732. numpy/random/tests/test_random.py +1723 -0
  733. numpy/random/tests/test_randomstate.py +2107 -0
  734. numpy/random/tests/test_randomstate_regression.py +249 -0
  735. numpy/random/tests/test_regression.py +174 -0
  736. numpy/random/tests/test_seed_sequence.py +103 -0
  737. numpy/random/tests/test_smoke.py +882 -0
  738. numpy/rec/__init__.py +2 -0
  739. numpy/rec/__init__.pyi +23 -0
  740. numpy/strings/__init__.py +2 -0
  741. numpy/strings/__init__.pyi +97 -0
  742. numpy/testing/__init__.py +22 -0
  743. numpy/testing/__init__.pyi +107 -0
  744. numpy/testing/_private/__init__.py +0 -0
  745. numpy/testing/_private/__init__.pyi +0 -0
  746. numpy/testing/_private/extbuild.py +247 -0
  747. numpy/testing/_private/extbuild.pyi +25 -0
  748. numpy/testing/_private/utils.py +2899 -0
  749. numpy/testing/_private/utils.pyi +501 -0
  750. numpy/testing/overrides.py +84 -0
  751. numpy/testing/overrides.pyi +10 -0
  752. numpy/testing/print_coercion_tables.py +207 -0
  753. numpy/testing/print_coercion_tables.pyi +26 -0
  754. numpy/testing/tests/__init__.py +0 -0
  755. numpy/testing/tests/test_utils.py +2147 -0
  756. numpy/tests/__init__.py +0 -0
  757. numpy/tests/test__all__.py +10 -0
  758. numpy/tests/test_configtool.py +51 -0
  759. numpy/tests/test_ctypeslib.py +406 -0
  760. numpy/tests/test_lazyloading.py +35 -0
  761. numpy/tests/test_matlib.py +59 -0
  762. numpy/tests/test_numpy_config.py +47 -0
  763. numpy/tests/test_numpy_version.py +54 -0
  764. numpy/tests/test_public_api.py +723 -0
  765. numpy/tests/test_reloading.py +69 -0
  766. numpy/tests/test_scripts.py +45 -0
  767. numpy/tests/test_warnings.py +81 -0
  768. numpy/typing/__init__.py +225 -0
  769. numpy/typing/__init__.pyi +8 -0
  770. numpy/typing/mypy_plugin.py +200 -0
  771. numpy/typing/tests/__init__.py +0 -0
  772. numpy/typing/tests/data/fail/arithmetic.pyi +126 -0
  773. numpy/typing/tests/data/fail/array_constructors.pyi +34 -0
  774. numpy/typing/tests/data/fail/array_like.pyi +15 -0
  775. numpy/typing/tests/data/fail/array_pad.pyi +6 -0
  776. numpy/typing/tests/data/fail/arrayprint.pyi +15 -0
  777. numpy/typing/tests/data/fail/arrayterator.pyi +14 -0
  778. numpy/typing/tests/data/fail/bitwise_ops.pyi +17 -0
  779. numpy/typing/tests/data/fail/char.pyi +60 -0
  780. numpy/typing/tests/data/fail/chararray.pyi +61 -0
  781. numpy/typing/tests/data/fail/comparisons.pyi +27 -0
  782. numpy/typing/tests/data/fail/constants.pyi +3 -0
  783. numpy/typing/tests/data/fail/datasource.pyi +16 -0
  784. numpy/typing/tests/data/fail/dtype.pyi +17 -0
  785. numpy/typing/tests/data/fail/einsumfunc.pyi +12 -0
  786. numpy/typing/tests/data/fail/flatiter.pyi +38 -0
  787. numpy/typing/tests/data/fail/fromnumeric.pyi +149 -0
  788. numpy/typing/tests/data/fail/histograms.pyi +12 -0
  789. numpy/typing/tests/data/fail/index_tricks.pyi +14 -0
  790. numpy/typing/tests/data/fail/lib_function_base.pyi +60 -0
  791. numpy/typing/tests/data/fail/lib_polynomial.pyi +29 -0
  792. numpy/typing/tests/data/fail/lib_utils.pyi +3 -0
  793. numpy/typing/tests/data/fail/lib_version.pyi +6 -0
  794. numpy/typing/tests/data/fail/linalg.pyi +48 -0
  795. numpy/typing/tests/data/fail/ma.pyi +152 -0
  796. numpy/typing/tests/data/fail/memmap.pyi +5 -0
  797. numpy/typing/tests/data/fail/modules.pyi +17 -0
  798. numpy/typing/tests/data/fail/multiarray.pyi +52 -0
  799. numpy/typing/tests/data/fail/ndarray.pyi +11 -0
  800. numpy/typing/tests/data/fail/ndarray_misc.pyi +49 -0
  801. numpy/typing/tests/data/fail/nditer.pyi +7 -0
  802. numpy/typing/tests/data/fail/nested_sequence.pyi +17 -0
  803. numpy/typing/tests/data/fail/npyio.pyi +24 -0
  804. numpy/typing/tests/data/fail/numerictypes.pyi +5 -0
  805. numpy/typing/tests/data/fail/random.pyi +62 -0
  806. numpy/typing/tests/data/fail/rec.pyi +17 -0
  807. numpy/typing/tests/data/fail/scalars.pyi +86 -0
  808. numpy/typing/tests/data/fail/shape.pyi +7 -0
  809. numpy/typing/tests/data/fail/shape_base.pyi +8 -0
  810. numpy/typing/tests/data/fail/stride_tricks.pyi +9 -0
  811. numpy/typing/tests/data/fail/strings.pyi +41 -0
  812. numpy/typing/tests/data/fail/testing.pyi +28 -0
  813. numpy/typing/tests/data/fail/twodim_base.pyi +39 -0
  814. numpy/typing/tests/data/fail/type_check.pyi +13 -0
  815. numpy/typing/tests/data/fail/ufunc_config.pyi +21 -0
  816. numpy/typing/tests/data/fail/ufunclike.pyi +21 -0
  817. numpy/typing/tests/data/fail/ufuncs.pyi +17 -0
  818. numpy/typing/tests/data/fail/warnings_and_errors.pyi +5 -0
  819. numpy/typing/tests/data/misc/extended_precision.pyi +9 -0
  820. numpy/typing/tests/data/mypy.ini +8 -0
  821. numpy/typing/tests/data/pass/arithmetic.py +614 -0
  822. numpy/typing/tests/data/pass/array_constructors.py +137 -0
  823. numpy/typing/tests/data/pass/array_like.py +37 -0
  824. numpy/typing/tests/data/pass/arrayprint.py +37 -0
  825. numpy/typing/tests/data/pass/arrayterator.py +28 -0
  826. numpy/typing/tests/data/pass/bitwise_ops.py +131 -0
  827. numpy/typing/tests/data/pass/comparisons.py +316 -0
  828. numpy/typing/tests/data/pass/dtype.py +57 -0
  829. numpy/typing/tests/data/pass/einsumfunc.py +36 -0
  830. numpy/typing/tests/data/pass/flatiter.py +26 -0
  831. numpy/typing/tests/data/pass/fromnumeric.py +272 -0
  832. numpy/typing/tests/data/pass/index_tricks.py +62 -0
  833. numpy/typing/tests/data/pass/lib_user_array.py +22 -0
  834. numpy/typing/tests/data/pass/lib_utils.py +19 -0
  835. numpy/typing/tests/data/pass/lib_version.py +18 -0
  836. numpy/typing/tests/data/pass/literal.py +52 -0
  837. numpy/typing/tests/data/pass/ma.py +199 -0
  838. numpy/typing/tests/data/pass/mod.py +149 -0
  839. numpy/typing/tests/data/pass/modules.py +45 -0
  840. numpy/typing/tests/data/pass/multiarray.py +77 -0
  841. numpy/typing/tests/data/pass/ndarray_conversion.py +81 -0
  842. numpy/typing/tests/data/pass/ndarray_misc.py +199 -0
  843. numpy/typing/tests/data/pass/ndarray_shape_manipulation.py +47 -0
  844. numpy/typing/tests/data/pass/nditer.py +4 -0
  845. numpy/typing/tests/data/pass/numeric.py +90 -0
  846. numpy/typing/tests/data/pass/numerictypes.py +17 -0
  847. numpy/typing/tests/data/pass/random.py +1498 -0
  848. numpy/typing/tests/data/pass/recfunctions.py +164 -0
  849. numpy/typing/tests/data/pass/scalars.py +262 -0
  850. numpy/typing/tests/data/pass/shape.py +19 -0
  851. numpy/typing/tests/data/pass/simple.py +170 -0
  852. numpy/typing/tests/data/pass/ufunc_config.py +64 -0
  853. numpy/typing/tests/data/pass/ufunclike.py +52 -0
  854. numpy/typing/tests/data/pass/ufuncs.py +16 -0
  855. numpy/typing/tests/data/pass/warnings_and_errors.py +6 -0
  856. numpy/typing/tests/data/reveal/arithmetic.pyi +726 -0
  857. numpy/typing/tests/data/reveal/array_api_info.pyi +70 -0
  858. numpy/typing/tests/data/reveal/array_constructors.pyi +331 -0
  859. numpy/typing/tests/data/reveal/arraypad.pyi +32 -0
  860. numpy/typing/tests/data/reveal/arrayprint.pyi +25 -0
  861. numpy/typing/tests/data/reveal/arraysetops.pyi +80 -0
  862. numpy/typing/tests/data/reveal/arrayterator.pyi +27 -0
  863. numpy/typing/tests/data/reveal/bitwise_ops.pyi +166 -0
  864. numpy/typing/tests/data/reveal/char.pyi +228 -0
  865. numpy/typing/tests/data/reveal/chararray.pyi +138 -0
  866. numpy/typing/tests/data/reveal/comparisons.pyi +264 -0
  867. numpy/typing/tests/data/reveal/constants.pyi +14 -0
  868. numpy/typing/tests/data/reveal/ctypeslib.pyi +86 -0
  869. numpy/typing/tests/data/reveal/datasource.pyi +23 -0
  870. numpy/typing/tests/data/reveal/dtype.pyi +166 -0
  871. numpy/typing/tests/data/reveal/einsumfunc.pyi +46 -0
  872. numpy/typing/tests/data/reveal/emath.pyi +54 -0
  873. numpy/typing/tests/data/reveal/fft.pyi +189 -0
  874. numpy/typing/tests/data/reveal/flatiter.pyi +86 -0
  875. numpy/typing/tests/data/reveal/fromnumeric.pyi +574 -0
  876. numpy/typing/tests/data/reveal/getlimits.pyi +53 -0
  877. numpy/typing/tests/data/reveal/histograms.pyi +69 -0
  878. numpy/typing/tests/data/reveal/index_tricks.pyi +148 -0
  879. numpy/typing/tests/data/reveal/lib_function_base.pyi +413 -0
  880. numpy/typing/tests/data/reveal/lib_polynomial.pyi +147 -0
  881. numpy/typing/tests/data/reveal/lib_utils.pyi +17 -0
  882. numpy/typing/tests/data/reveal/lib_version.pyi +20 -0
  883. numpy/typing/tests/data/reveal/linalg.pyi +517 -0
  884. numpy/typing/tests/data/reveal/ma.pyi +1103 -0
  885. numpy/typing/tests/data/reveal/matrix.pyi +73 -0
  886. numpy/typing/tests/data/reveal/memmap.pyi +21 -0
  887. numpy/typing/tests/data/reveal/mod.pyi +179 -0
  888. numpy/typing/tests/data/reveal/modules.pyi +51 -0
  889. numpy/typing/tests/data/reveal/multiarray.pyi +336 -0
  890. numpy/typing/tests/data/reveal/nbit_base_example.pyi +17 -0
  891. numpy/typing/tests/data/reveal/ndarray_assignability.pyi +79 -0
  892. numpy/typing/tests/data/reveal/ndarray_conversion.pyi +83 -0
  893. numpy/typing/tests/data/reveal/ndarray_misc.pyi +428 -0
  894. numpy/typing/tests/data/reveal/ndarray_shape_manipulation.pyi +47 -0
  895. numpy/typing/tests/data/reveal/nditer.pyi +49 -0
  896. numpy/typing/tests/data/reveal/nested_sequence.pyi +25 -0
  897. numpy/typing/tests/data/reveal/npyio.pyi +85 -0
  898. numpy/typing/tests/data/reveal/numeric.pyi +176 -0
  899. numpy/typing/tests/data/reveal/numerictypes.pyi +16 -0
  900. numpy/typing/tests/data/reveal/polynomial_polybase.pyi +216 -0
  901. numpy/typing/tests/data/reveal/polynomial_polyutils.pyi +218 -0
  902. numpy/typing/tests/data/reveal/polynomial_series.pyi +138 -0
  903. numpy/typing/tests/data/reveal/random.pyi +1357 -0
  904. numpy/typing/tests/data/reveal/rec.pyi +177 -0
  905. numpy/typing/tests/data/reveal/scalars.pyi +288 -0
  906. numpy/typing/tests/data/reveal/shape.pyi +13 -0
  907. numpy/typing/tests/data/reveal/shape_base.pyi +84 -0
  908. numpy/typing/tests/data/reveal/stride_tricks.pyi +27 -0
  909. numpy/typing/tests/data/reveal/strings.pyi +198 -0
  910. numpy/typing/tests/data/reveal/testing.pyi +196 -0
  911. numpy/typing/tests/data/reveal/twodim_base.pyi +231 -0
  912. numpy/typing/tests/data/reveal/type_check.pyi +94 -0
  913. numpy/typing/tests/data/reveal/ufunc_config.pyi +30 -0
  914. numpy/typing/tests/data/reveal/ufunclike.pyi +31 -0
  915. numpy/typing/tests/data/reveal/ufuncs.pyi +142 -0
  916. numpy/typing/tests/data/reveal/warnings_and_errors.pyi +11 -0
  917. numpy/typing/tests/test_isfile.py +35 -0
  918. numpy/typing/tests/test_runtime.py +103 -0
  919. numpy/typing/tests/test_typing.py +207 -0
  920. numpy/version.py +11 -0
  921. numpy/version.pyi +9 -0
  922. numpy-2.5.2.dist-info/METADATA +139 -0
  923. numpy-2.5.2.dist-info/RECORD +942 -0
  924. numpy-2.5.2.dist-info/WHEEL +4 -0
  925. numpy-2.5.2.dist-info/entry_points.txt +13 -0
  926. numpy-2.5.2.dist-info/licenses/LICENSE.txt +914 -0
  927. numpy-2.5.2.dist-info/licenses/numpy/_core/include/numpy/libdivide/LICENSE.txt +21 -0
  928. numpy-2.5.2.dist-info/licenses/numpy/_core/src/common/pythoncapi-compat/COPYING +14 -0
  929. numpy-2.5.2.dist-info/licenses/numpy/_core/src/highway/LICENSE +371 -0
  930. numpy-2.5.2.dist-info/licenses/numpy/_core/src/multiarray/dragon4_LICENSE.txt +27 -0
  931. numpy-2.5.2.dist-info/licenses/numpy/_core/src/npysort/x86-simd-sort/LICENSE.md +28 -0
  932. numpy-2.5.2.dist-info/licenses/numpy/_core/src/umath/svml/LICENSE +30 -0
  933. numpy-2.5.2.dist-info/licenses/numpy/fft/pocketfft/LICENSE.md +25 -0
  934. numpy-2.5.2.dist-info/licenses/numpy/linalg/lapack_lite/LICENSE.txt +48 -0
  935. numpy-2.5.2.dist-info/licenses/numpy/ma/LICENSE +24 -0
  936. numpy-2.5.2.dist-info/licenses/numpy/random/LICENSE.md +71 -0
  937. numpy-2.5.2.dist-info/licenses/numpy/random/src/distributions/LICENSE.md +61 -0
  938. numpy-2.5.2.dist-info/licenses/numpy/random/src/mt19937/LICENSE.md +61 -0
  939. numpy-2.5.2.dist-info/licenses/numpy/random/src/pcg64/LICENSE.md +22 -0
  940. numpy-2.5.2.dist-info/licenses/numpy/random/src/philox/LICENSE.md +31 -0
  941. numpy-2.5.2.dist-info/licenses/numpy/random/src/sfc64/LICENSE.md +27 -0
  942. numpy-2.5.2.dist-info/licenses/numpy/random/src/splitmix64/LICENSE.md +9 -0
@@ -0,0 +1,3220 @@
1
+ import datetime
2
+ import pickle
3
+ import warnings
4
+ from typing import Final
5
+ from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
6
+
7
+ import pytest
8
+
9
+ import numpy
10
+ import numpy as np
11
+ from numpy.testing import (
12
+ IS_WASM,
13
+ assert_,
14
+ assert_array_equal,
15
+ assert_equal,
16
+ assert_raises,
17
+ assert_raises_regex,
18
+ )
19
+
20
+ try:
21
+ RecursionError
22
+ except NameError:
23
+ RecursionError = RuntimeError # python < 3.5
24
+
25
+ try:
26
+ ZoneInfo("US/Central")
27
+ _has_tz = True
28
+ except ZoneInfoNotFoundError:
29
+ _has_tz = False
30
+
31
+ def _assert_equal_hash(v1, v2):
32
+ assert v1 == v2
33
+ assert hash(v1) == hash(v2)
34
+ assert v2 in {v1}
35
+
36
+
37
+ class TestDateTime:
38
+ generic_unit_deprecation_message: Final[str] = (
39
+ "The 'generic' unit for NumPy timedelta is deprecated"
40
+ )
41
+
42
+ def test_string(self):
43
+ msg = "no explicit representation of timezones available for " \
44
+ "np.datetime64"
45
+ with pytest.warns(UserWarning, match=msg):
46
+ np.datetime64('2000-01-01T00+01')
47
+
48
+ def test_datetime(self):
49
+ msg = "no explicit representation of timezones available for " \
50
+ "np.datetime64"
51
+ with pytest.warns(UserWarning, match=msg):
52
+ t0 = np.datetime64('2023-06-09T12:18:40Z', 'ns')
53
+
54
+ t0 = np.datetime64('2023-06-09T12:18:40', 'ns')
55
+
56
+ def test_datetime_dtype_creation(self):
57
+ for unit in ['Y', 'M', 'W', 'D',
58
+ 'h', 'm', 's', 'ms', 'us',
59
+ 'μs', # alias for us
60
+ 'ns', 'ps', 'fs', 'as']:
61
+ dt1 = np.dtype(f'M8[750{unit}]')
62
+ assert_(dt1 == np.dtype(f'datetime64[750{unit}]'))
63
+ dt2 = np.dtype(f'm8[{unit}]')
64
+ assert_(dt2 == np.dtype(f'timedelta64[{unit}]'))
65
+
66
+ # Generic units shouldn't add [] to the end
67
+ assert_equal(str(np.dtype("M8")), "datetime64")
68
+
69
+ # Should be possible to specify the endianness
70
+ assert_equal(np.dtype("=M8"), np.dtype("M8"))
71
+ assert_equal(np.dtype("=M8[s]"), np.dtype("M8[s]"))
72
+ assert_(np.dtype(">M8") == np.dtype("M8") or
73
+ np.dtype("<M8") == np.dtype("M8"))
74
+ assert_(np.dtype(">M8[D]") == np.dtype("M8[D]") or
75
+ np.dtype("<M8[D]") == np.dtype("M8[D]"))
76
+ assert_(np.dtype(">M8") != np.dtype("<M8"))
77
+
78
+ assert_equal(np.dtype("=m8"), np.dtype("m8"))
79
+ assert_equal(np.dtype("=m8[s]"), np.dtype("m8[s]"))
80
+ assert_(np.dtype(">m8") == np.dtype("m8") or
81
+ np.dtype("<m8") == np.dtype("m8"))
82
+ assert_(np.dtype(">m8[D]") == np.dtype("m8[D]") or
83
+ np.dtype("<m8[D]") == np.dtype("m8[D]"))
84
+ assert_(np.dtype(">m8") != np.dtype("<m8"))
85
+
86
+ # Check that the parser rejects bad datetime types
87
+ assert_raises(TypeError, np.dtype, 'M8[badunit]')
88
+ assert_raises(TypeError, np.dtype, 'm8[badunit]')
89
+ assert_raises(TypeError, np.dtype, 'M8[YY]')
90
+ assert_raises(TypeError, np.dtype, 'm8[YY]')
91
+ assert_raises(TypeError, np.dtype, 'm4')
92
+ assert_raises(TypeError, np.dtype, 'M7')
93
+ assert_raises(TypeError, np.dtype, 'm7')
94
+ assert_raises(TypeError, np.dtype, 'M16')
95
+ assert_raises(TypeError, np.dtype, 'm16')
96
+ assert_raises(TypeError, np.dtype, 'M8[3000000000ps]')
97
+
98
+ def test_datetime_casting_rules(self):
99
+ # Cannot cast safely/same_kind between timedelta and datetime
100
+ assert_(not np.can_cast('m8', 'M8', casting='same_kind'))
101
+ assert_(not np.can_cast('M8', 'm8', casting='same_kind'))
102
+ assert_(not np.can_cast('m8', 'M8', casting='safe'))
103
+ assert_(not np.can_cast('M8', 'm8', casting='safe'))
104
+
105
+ # Can cast safely/same_kind from integer to timedelta
106
+ assert_(np.can_cast('i8', 'm8', casting='same_kind'))
107
+ assert_(np.can_cast('i8', 'm8', casting='safe'))
108
+ assert_(np.can_cast('i4', 'm8', casting='same_kind'))
109
+ assert_(np.can_cast('i4', 'm8', casting='safe'))
110
+ assert_(np.can_cast('u4', 'm8', casting='same_kind'))
111
+ assert_(np.can_cast('u4', 'm8', casting='safe'))
112
+
113
+ # Cannot cast safely from unsigned integer of the same size, which
114
+ # could overflow
115
+ assert_(np.can_cast('u8', 'm8', casting='same_kind'))
116
+ assert_(not np.can_cast('u8', 'm8', casting='safe'))
117
+
118
+ # Cannot cast safely/same_kind from float to timedelta
119
+ assert_(not np.can_cast('f4', 'm8', casting='same_kind'))
120
+ assert_(not np.can_cast('f4', 'm8', casting='safe'))
121
+
122
+ # Cannot cast safely/same_kind from integer to datetime
123
+ assert_(not np.can_cast('i8', 'M8', casting='same_kind'))
124
+ assert_(not np.can_cast('i8', 'M8', casting='safe'))
125
+
126
+ # Cannot cast safely/same_kind from bool to datetime
127
+ assert_(not np.can_cast('b1', 'M8', casting='same_kind'))
128
+ assert_(not np.can_cast('b1', 'M8', casting='safe'))
129
+ # Can cast safely/same_kind from bool to timedelta
130
+ assert_(np.can_cast('b1', 'm8', casting='same_kind'))
131
+ assert_(np.can_cast('b1', 'm8', casting='safe'))
132
+
133
+ # Can cast datetime safely from months/years to days
134
+ assert_(np.can_cast('M8[M]', 'M8[D]', casting='safe'))
135
+ assert_(np.can_cast('M8[Y]', 'M8[D]', casting='safe'))
136
+ # Cannot cast timedelta safely from months/years to days
137
+ assert_(not np.can_cast('m8[M]', 'm8[D]', casting='safe'))
138
+ assert_(not np.can_cast('m8[Y]', 'm8[D]', casting='safe'))
139
+ # Can cast datetime same_kind from months/years to days
140
+ assert_(np.can_cast('M8[M]', 'M8[D]', casting='same_kind'))
141
+ assert_(np.can_cast('M8[Y]', 'M8[D]', casting='same_kind'))
142
+ # Can't cast timedelta same_kind from months/years to days
143
+ assert_(not np.can_cast('m8[M]', 'm8[D]', casting='same_kind'))
144
+ assert_(not np.can_cast('m8[Y]', 'm8[D]', casting='same_kind'))
145
+ # Can cast datetime same_kind across the date/time boundary
146
+ assert_(np.can_cast('M8[D]', 'M8[h]', casting='same_kind'))
147
+ # Can cast timedelta same_kind across the date/time boundary
148
+ assert_(np.can_cast('m8[D]', 'm8[h]', casting='same_kind'))
149
+ assert_(np.can_cast('m8[h]', 'm8[D]', casting='same_kind'))
150
+
151
+ # Cannot cast safely if the integer multiplier doesn't divide
152
+ assert_(not np.can_cast('M8[7h]', 'M8[3h]', casting='safe'))
153
+ assert_(not np.can_cast('M8[3h]', 'M8[6h]', casting='safe'))
154
+ # But can cast same_kind
155
+ assert_(np.can_cast('M8[7h]', 'M8[3h]', casting='same_kind'))
156
+ # Can cast safely if the integer multiplier does divide
157
+ assert_(np.can_cast('M8[6h]', 'M8[3h]', casting='safe'))
158
+
159
+ # We can always cast types with generic units (corresponding to NaT) to
160
+ # more specific types
161
+ assert_(np.can_cast('m8', 'm8[h]', casting='same_kind'))
162
+ assert_(np.can_cast('m8', 'm8[h]', casting='safe'))
163
+ assert_(np.can_cast('M8', 'M8[h]', casting='same_kind'))
164
+ assert_(np.can_cast('M8', 'M8[h]', casting='safe'))
165
+ # but not the other way around
166
+ assert_(not np.can_cast('m8[h]', 'm8', casting='same_kind'))
167
+ assert_(not np.can_cast('m8[h]', 'm8', casting='safe'))
168
+ assert_(not np.can_cast('M8[h]', 'M8', casting='same_kind'))
169
+ assert_(not np.can_cast('M8[h]', 'M8', casting='safe'))
170
+
171
+ def test_datetime_prefix_conversions(self):
172
+ # regression tests related to gh-19631;
173
+ # test metric prefixes from seconds down to
174
+ # attoseconds for bidirectional conversions
175
+ smaller_units = ['M8[7000ms]',
176
+ 'M8[2000us]',
177
+ 'M8[1000ns]',
178
+ 'M8[5000ns]',
179
+ 'M8[2000ps]',
180
+ 'M8[9000fs]',
181
+ 'M8[1000as]',
182
+ 'M8[2000000ps]',
183
+ 'M8[1000000as]',
184
+ 'M8[2000000000ps]',
185
+ 'M8[1000000000as]']
186
+ larger_units = ['M8[7s]',
187
+ 'M8[2ms]',
188
+ 'M8[us]',
189
+ 'M8[5us]',
190
+ 'M8[2ns]',
191
+ 'M8[9ps]',
192
+ 'M8[1fs]',
193
+ 'M8[2us]',
194
+ 'M8[1ps]',
195
+ 'M8[2ms]',
196
+ 'M8[1ns]']
197
+ for larger_unit, smaller_unit in zip(larger_units, smaller_units):
198
+ assert np.can_cast(larger_unit, smaller_unit, casting='safe')
199
+ assert np.can_cast(smaller_unit, larger_unit, casting='safe')
200
+
201
+ @pytest.mark.parametrize("unit", [
202
+ "s", "ms", "us", "ns", "ps", "fs", "as"])
203
+ def test_prohibit_negative_datetime(self, unit):
204
+ with assert_raises(TypeError):
205
+ np.array([1], dtype=f"M8[-1{unit}]")
206
+
207
+ def test_compare_generic_nat(self):
208
+ # regression tests for gh-6452
209
+ with pytest.warns(
210
+ DeprecationWarning,
211
+ match=self.generic_unit_deprecation_message,
212
+ ):
213
+ assert_(
214
+ np.datetime64("NaT") != np.datetime64("2000") + np.timedelta64("NaT")
215
+ )
216
+ assert_(np.datetime64("NaT") != np.datetime64("NaT", "us"))
217
+ assert_(np.datetime64('NaT', 'us') != np.datetime64('NaT'))
218
+
219
+ @pytest.mark.parametrize("size", [
220
+ 3, 21, 217, 1000])
221
+ def test_datetime_nat_argsort_stability(self, size):
222
+ # NaT < NaT should be False internally for
223
+ # sort stability
224
+ expected = np.arange(size)
225
+ arr = np.tile(np.datetime64('NaT', 'D'), size)
226
+ assert_equal(np.argsort(arr, kind='mergesort'), expected)
227
+
228
+ @pytest.mark.parametrize("size", [
229
+ 3, 21, 217, 1000])
230
+ def test_timedelta_nat_argsort_stability(self, size):
231
+ # NaT < NaT should be False internally for
232
+ # sort stability
233
+ expected = np.arange(size)
234
+ arr = np.tile(np.timedelta64('NaT', 's'), size)
235
+ assert_equal(np.argsort(arr, kind='mergesort'), expected)
236
+
237
+ @pytest.mark.parametrize("arr, expected", [
238
+ # the example provided in gh-12629
239
+ (['NaT', 1, 2, 3],
240
+ [1, 2, 3, 'NaT']),
241
+ # multiple NaTs
242
+ (['NaT', 9, 'NaT', -707],
243
+ [-707, 9, 'NaT', 'NaT']),
244
+ # this sort explores another code path for NaT
245
+ ([1, -2, 3, 'NaT'],
246
+ [-2, 1, 3, 'NaT']),
247
+ # 2-D array
248
+ ([[51, -220, 'NaT'],
249
+ [-17, 'NaT', -90]],
250
+ [[-220, 51, 'NaT'],
251
+ [-90, -17, 'NaT']]),
252
+ ])
253
+ @pytest.mark.parametrize("dtype", [
254
+ 'M8[ns]', 'M8[us]',
255
+ 'm8[ns]', 'm8[us]'])
256
+ def test_datetime_timedelta_sort_nat(self, arr, expected, dtype):
257
+ # fix for gh-12629 and gh-15063; NaT sorting to end of array
258
+ arr = np.array(arr, dtype=dtype)
259
+ expected = np.array(expected, dtype=dtype)
260
+ arr.sort()
261
+ assert_equal(arr, expected)
262
+
263
+ def test_datetime_scalar_construction(self):
264
+ # Construct with different units
265
+ assert_equal(np.datetime64('1950-03-12', 'D'),
266
+ np.datetime64('1950-03-12'))
267
+ assert_equal(np.datetime64('1950-03-12T13', 's'),
268
+ np.datetime64('1950-03-12T13', 'm'))
269
+
270
+ with pytest.warns(
271
+ DeprecationWarning,
272
+ match=self.generic_unit_deprecation_message
273
+ ):
274
+ # Default construction means NaT
275
+ assert_equal(np.datetime64(), np.datetime64('NaT'))
276
+
277
+ # Some basic strings and repr
278
+ assert_equal(str(np.datetime64('NaT')), 'NaT')
279
+ assert_equal(repr(np.datetime64('NaT')),
280
+ "np.datetime64('NaT','generic')")
281
+
282
+ # None gets constructed as NaT
283
+ assert_equal(np.datetime64(None), np.datetime64('NaT'))
284
+
285
+ assert_equal(str(np.datetime64('2011-02')), '2011-02')
286
+ assert_equal(repr(np.datetime64('2011-02')),
287
+ "np.datetime64('2011-02')")
288
+ assert_equal(repr(np.datetime64('NaT', 'D').astype(np.dtype("datetime64[ns]"))),
289
+ "np.datetime64('NaT','ns')")
290
+
291
+ with pytest.warns(
292
+ DeprecationWarning,
293
+ match=self.generic_unit_deprecation_message
294
+ ):
295
+ # Default construction of NaT is in generic units
296
+ assert_equal(np.datetime64().dtype, np.dtype('M8'))
297
+
298
+ assert_equal(np.datetime64('NaT').dtype, np.dtype('M8'))
299
+
300
+ # Construction from integers requires a specified unit
301
+ assert_raises(ValueError, np.datetime64, 17)
302
+
303
+ # When constructing from a scalar or zero-dimensional array,
304
+ # it either keeps the units or you can override them.
305
+ a = np.datetime64('2000-03-18T16', 'h')
306
+ b = np.array('2000-03-18T16', dtype='M8[h]')
307
+
308
+ assert_equal(a.dtype, np.dtype('M8[h]'))
309
+ assert_equal(b.dtype, np.dtype('M8[h]'))
310
+
311
+ assert_equal(np.datetime64(a), a)
312
+ assert_equal(np.datetime64(a).dtype, np.dtype('M8[h]'))
313
+
314
+ assert_equal(np.datetime64(b), a)
315
+ assert_equal(np.datetime64(b).dtype, np.dtype('M8[h]'))
316
+
317
+ assert_equal(np.datetime64(a, 's'), a)
318
+ assert_equal(np.datetime64(a, 's').dtype, np.dtype('M8[s]'))
319
+
320
+ assert_equal(np.datetime64(b, 's'), a)
321
+ assert_equal(np.datetime64(b, 's').dtype, np.dtype('M8[s]'))
322
+
323
+ # Construction from datetime.date
324
+ assert_equal(np.datetime64('1945-03-25'),
325
+ np.datetime64(datetime.date(1945, 3, 25)))
326
+ assert_equal(np.datetime64('2045-03-25', 'D'),
327
+ np.datetime64(datetime.date(2045, 3, 25), 'D'))
328
+ # Construction from datetime.datetime
329
+ assert_equal(np.datetime64('1980-01-25T14:36:22.5'),
330
+ np.datetime64(datetime.datetime(1980, 1, 25,
331
+ 14, 36, 22, 500000)))
332
+
333
+ # Construction with time units from a date is okay
334
+ assert_equal(np.datetime64('1920-03-13', 'h'),
335
+ np.datetime64('1920-03-13T00'))
336
+ assert_equal(np.datetime64('1920-03', 'm'),
337
+ np.datetime64('1920-03-01T00:00'))
338
+ assert_equal(np.datetime64('1920', 's'),
339
+ np.datetime64('1920-01-01T00:00:00'))
340
+ assert_equal(np.datetime64(datetime.date(2045, 3, 25), 'ms'),
341
+ np.datetime64('2045-03-25T00:00:00.000'))
342
+
343
+ # Construction with date units from a datetime is also okay
344
+ assert_equal(np.datetime64('1920-03-13T18', 'D'),
345
+ np.datetime64('1920-03-13'))
346
+ assert_equal(np.datetime64('1920-03-13T18:33:12', 'M'),
347
+ np.datetime64('1920-03'))
348
+ assert_equal(np.datetime64('1920-03-13T18:33:12.5', 'Y'),
349
+ np.datetime64('1920'))
350
+
351
+ def test_datetime_scalar_construction_timezone(self):
352
+ msg = "no explicit representation of timezones available for " \
353
+ "np.datetime64"
354
+ # verify that supplying an explicit timezone works, but is deprecated
355
+ with pytest.warns(UserWarning, match=msg):
356
+ assert_equal(np.datetime64('2000-01-01T00Z'),
357
+ np.datetime64('2000-01-01T00'))
358
+ with pytest.warns(UserWarning, match=msg):
359
+ assert_equal(np.datetime64('2000-01-01T00-08'),
360
+ np.datetime64('2000-01-01T08'))
361
+
362
+ def test_datetime_array_find_type(self):
363
+ dt = np.datetime64('1970-01-01', 'M')
364
+ arr = np.array([dt])
365
+ assert_equal(arr.dtype, np.dtype('M8[M]'))
366
+
367
+ # at the moment, we don't automatically convert these to datetime64
368
+
369
+ dt = datetime.date(1970, 1, 1)
370
+ arr = np.array([dt])
371
+ assert_equal(arr.dtype, np.dtype('O'))
372
+
373
+ dt = datetime.datetime(1970, 1, 1, 12, 30, 40)
374
+ arr = np.array([dt])
375
+ assert_equal(arr.dtype, np.dtype('O'))
376
+
377
+ # find "supertype" for non-dates and dates
378
+
379
+ b = np.bool(True)
380
+ dm = np.datetime64('1970-01-01', 'M')
381
+ d = datetime.date(1970, 1, 1)
382
+ dt = datetime.datetime(1970, 1, 1, 12, 30, 40)
383
+
384
+ arr = np.array([b, dm])
385
+ assert_equal(arr.dtype, np.dtype('O'))
386
+
387
+ arr = np.array([b, d])
388
+ assert_equal(arr.dtype, np.dtype('O'))
389
+
390
+ arr = np.array([b, dt])
391
+ assert_equal(arr.dtype, np.dtype('O'))
392
+
393
+ arr = np.array([d, d]).astype('datetime64')
394
+ assert_equal(arr.dtype, np.dtype('M8[D]'))
395
+
396
+ arr = np.array([dt, dt]).astype('datetime64')
397
+ assert_equal(arr.dtype, np.dtype('M8[us]'))
398
+
399
+ @pytest.mark.parametrize("unit", [
400
+ # test all date / time units and use
401
+ # "generic" to select generic unit
402
+ ("Y"), ("M"), ("W"), ("D"), ("h"), ("m"),
403
+ ("s"), ("ms"), ("us"), ("ns"), ("ps"),
404
+ ("fs"), ("as"), ("generic")])
405
+ def test_timedelta_np_int_construction(self, unit):
406
+ # regression test for gh-7617
407
+ if unit != "generic":
408
+ assert_equal(np.timedelta64(np.int64(123), unit),
409
+ np.timedelta64(123, unit))
410
+ else:
411
+ with pytest.warns(
412
+ DeprecationWarning,
413
+ match=self.generic_unit_deprecation_message
414
+ ):
415
+ assert_equal(np.timedelta64(np.int64(123)), np.timedelta64(123))
416
+
417
+ def test_timedelta_scalar_construction(self):
418
+ # Construct with different units
419
+ assert_equal(np.timedelta64(7, 'D'),
420
+ np.timedelta64(1, 'W'))
421
+ assert_equal(np.timedelta64(120, 's'),
422
+ np.timedelta64(2, 'm'))
423
+
424
+ with pytest.warns(
425
+ DeprecationWarning,
426
+ match=self.generic_unit_deprecation_message,
427
+ ):
428
+ # Default construction means 0
429
+ assert_equal(np.timedelta64(), np.timedelta64(0))
430
+
431
+ # None gets constructed as NaT
432
+ assert_equal(np.timedelta64(None, 's'), np.timedelta64('NaT', 's'))
433
+
434
+ # Some basic strings and repr
435
+ assert_equal(str(np.timedelta64('NaT', 'ns')), 'NaT')
436
+ with pytest.warns(
437
+ DeprecationWarning,
438
+ match=self.generic_unit_deprecation_message,
439
+ ):
440
+ assert_equal(repr(np.timedelta64("NaT")), "np.timedelta64('NaT')")
441
+ assert_equal(str(np.timedelta64(3, 's')), '3 seconds')
442
+ assert_equal(repr(np.timedelta64(-3, 's')),
443
+ "np.timedelta64(-3,'s')")
444
+
445
+ with pytest.warns(
446
+ DeprecationWarning,
447
+ match=self.generic_unit_deprecation_message,
448
+ ):
449
+ assert_equal(repr(np.timedelta64(12)),
450
+ "np.timedelta64(12)")
451
+
452
+ # Construction from an integer produces generic units
453
+ assert_equal(np.timedelta64(12).dtype, np.dtype('m8'))
454
+
455
+ # When constructing from a scalar or zero-dimensional array,
456
+ # it either keeps the units or you can override them.
457
+ a = np.timedelta64(2, 'h')
458
+ b = np.array(2, dtype='m8[h]')
459
+
460
+ assert_equal(a.dtype, np.dtype('m8[h]'))
461
+ assert_equal(b.dtype, np.dtype('m8[h]'))
462
+
463
+ assert_equal(np.timedelta64(a), a)
464
+ assert_equal(np.timedelta64(a).dtype, np.dtype('m8[h]'))
465
+
466
+ assert_equal(np.timedelta64(b), a)
467
+ assert_equal(np.timedelta64(b).dtype, np.dtype('m8[h]'))
468
+
469
+ assert_equal(np.timedelta64(a, 's'), a)
470
+ assert_equal(np.timedelta64(a, 's').dtype, np.dtype('m8[s]'))
471
+
472
+ assert_equal(np.timedelta64(b, 's'), a)
473
+ assert_equal(np.timedelta64(b, 's').dtype, np.dtype('m8[s]'))
474
+
475
+ # Construction from datetime.timedelta
476
+ assert_equal(np.timedelta64(5, 'D'),
477
+ np.timedelta64(datetime.timedelta(days=5)))
478
+ assert_equal(np.timedelta64(102347621, 's'),
479
+ np.timedelta64(datetime.timedelta(seconds=102347621)))
480
+ assert_equal(np.timedelta64(-10234760000, 'us'),
481
+ np.timedelta64(datetime.timedelta(
482
+ microseconds=-10234760000)))
483
+ assert_equal(np.timedelta64(10234760000, 'us'),
484
+ np.timedelta64(datetime.timedelta(
485
+ microseconds=10234760000)))
486
+ assert_equal(np.timedelta64(1023476, 'ms'),
487
+ np.timedelta64(datetime.timedelta(milliseconds=1023476)))
488
+ assert_equal(np.timedelta64(10, 'm'),
489
+ np.timedelta64(datetime.timedelta(minutes=10)))
490
+ assert_equal(np.timedelta64(281, 'h'),
491
+ np.timedelta64(datetime.timedelta(hours=281)))
492
+ assert_equal(np.timedelta64(28, 'W'),
493
+ np.timedelta64(datetime.timedelta(weeks=28)))
494
+
495
+ # Cannot construct across nonlinear time unit boundaries
496
+ a = np.timedelta64(3, 's')
497
+ assert_raises(TypeError, np.timedelta64, a, 'M')
498
+ assert_raises(TypeError, np.timedelta64, a, 'Y')
499
+ a = np.timedelta64(6, 'M')
500
+ assert_raises(TypeError, np.timedelta64, a, 'D')
501
+ assert_raises(TypeError, np.timedelta64, a, 'h')
502
+ a = np.timedelta64(1, 'Y')
503
+ assert_raises(TypeError, np.timedelta64, a, 'D')
504
+ assert_raises(TypeError, np.timedelta64, a, 'm')
505
+ a = datetime.timedelta(seconds=3)
506
+ assert_raises(TypeError, np.timedelta64, a, 'M')
507
+ assert_raises(TypeError, np.timedelta64, a, 'Y')
508
+ a = datetime.timedelta(weeks=3)
509
+ assert_raises(TypeError, np.timedelta64, a, 'M')
510
+ assert_raises(TypeError, np.timedelta64, a, 'Y')
511
+ a = datetime.timedelta()
512
+ assert_raises(TypeError, np.timedelta64, a, 'M')
513
+ assert_raises(TypeError, np.timedelta64, a, 'Y')
514
+
515
+ def test_timedelta_object_array_conversion(self):
516
+ # Regression test for gh-11096
517
+ inputs = [datetime.timedelta(28),
518
+ datetime.timedelta(30),
519
+ datetime.timedelta(31)]
520
+ expected = np.array([28, 30, 31], dtype='timedelta64[D]')
521
+ actual = np.array(inputs, dtype='timedelta64[D]')
522
+ assert_equal(expected, actual)
523
+
524
+ def test_timedelta_0_dim_object_array_conversion(self):
525
+ # Regression test for gh-11151
526
+ test = np.array(datetime.timedelta(seconds=20))
527
+ actual = test.astype(np.timedelta64)
528
+ # expected value from the array constructor workaround
529
+ # described in above issue
530
+ expected = np.array(datetime.timedelta(seconds=20),
531
+ np.timedelta64)
532
+ assert_equal(actual, expected)
533
+
534
+ def test_timedelta_nat_format(self):
535
+ # gh-17552
536
+ with pytest.warns(
537
+ DeprecationWarning,
538
+ match=self.generic_unit_deprecation_message,
539
+ ):
540
+ assert_equal('NaT', f'{np.timedelta64("nat")}')
541
+
542
+ def test_timedelta_scalar_construction_units(self):
543
+ # String construction detecting units
544
+ assert_equal(np.datetime64('2010').dtype,
545
+ np.dtype('M8[Y]'))
546
+ assert_equal(np.datetime64('2010-03').dtype,
547
+ np.dtype('M8[M]'))
548
+ assert_equal(np.datetime64('2010-03-12').dtype,
549
+ np.dtype('M8[D]'))
550
+ assert_equal(np.datetime64('2010-03-12T17').dtype,
551
+ np.dtype('M8[h]'))
552
+ assert_equal(np.datetime64('2010-03-12T17:15').dtype,
553
+ np.dtype('M8[m]'))
554
+ assert_equal(np.datetime64('2010-03-12T17:15:08').dtype,
555
+ np.dtype('M8[s]'))
556
+
557
+ assert_equal(np.datetime64('2010-03-12T17:15:08.1').dtype,
558
+ np.dtype('M8[ms]'))
559
+ assert_equal(np.datetime64('2010-03-12T17:15:08.12').dtype,
560
+ np.dtype('M8[ms]'))
561
+ assert_equal(np.datetime64('2010-03-12T17:15:08.123').dtype,
562
+ np.dtype('M8[ms]'))
563
+
564
+ assert_equal(np.datetime64('2010-03-12T17:15:08.1234').dtype,
565
+ np.dtype('M8[us]'))
566
+ assert_equal(np.datetime64('2010-03-12T17:15:08.12345').dtype,
567
+ np.dtype('M8[us]'))
568
+ assert_equal(np.datetime64('2010-03-12T17:15:08.123456').dtype,
569
+ np.dtype('M8[us]'))
570
+
571
+ assert_equal(np.datetime64('1970-01-01T00:00:02.1234567').dtype,
572
+ np.dtype('M8[ns]'))
573
+ assert_equal(np.datetime64('1970-01-01T00:00:02.12345678').dtype,
574
+ np.dtype('M8[ns]'))
575
+ assert_equal(np.datetime64('1970-01-01T00:00:02.123456789').dtype,
576
+ np.dtype('M8[ns]'))
577
+
578
+ assert_equal(np.datetime64('1970-01-01T00:00:02.1234567890').dtype,
579
+ np.dtype('M8[ps]'))
580
+ assert_equal(np.datetime64('1970-01-01T00:00:02.12345678901').dtype,
581
+ np.dtype('M8[ps]'))
582
+ assert_equal(np.datetime64('1970-01-01T00:00:02.123456789012').dtype,
583
+ np.dtype('M8[ps]'))
584
+
585
+ assert_equal(np.datetime64(
586
+ '1970-01-01T00:00:02.1234567890123').dtype,
587
+ np.dtype('M8[fs]'))
588
+ assert_equal(np.datetime64(
589
+ '1970-01-01T00:00:02.12345678901234').dtype,
590
+ np.dtype('M8[fs]'))
591
+ assert_equal(np.datetime64(
592
+ '1970-01-01T00:00:02.123456789012345').dtype,
593
+ np.dtype('M8[fs]'))
594
+
595
+ assert_equal(np.datetime64(
596
+ '1970-01-01T00:00:02.1234567890123456').dtype,
597
+ np.dtype('M8[as]'))
598
+ assert_equal(np.datetime64(
599
+ '1970-01-01T00:00:02.12345678901234567').dtype,
600
+ np.dtype('M8[as]'))
601
+ assert_equal(np.datetime64(
602
+ '1970-01-01T00:00:02.123456789012345678').dtype,
603
+ np.dtype('M8[as]'))
604
+
605
+ # Python date object
606
+ assert_equal(np.datetime64(datetime.date(2010, 4, 16)).dtype,
607
+ np.dtype('M8[D]'))
608
+
609
+ # Python datetime object
610
+ assert_equal(np.datetime64(
611
+ datetime.datetime(2010, 4, 16, 13, 45, 18)).dtype,
612
+ np.dtype('M8[us]'))
613
+
614
+ # 'today' special value
615
+ assert_equal(np.datetime64('today').dtype,
616
+ np.dtype('M8[D]'))
617
+
618
+ # 'now' special value
619
+ assert_equal(np.datetime64('now').dtype,
620
+ np.dtype('M8[s]'))
621
+
622
+ def test_datetime_nat_casting(self):
623
+ a = np.array('NaT', dtype='M8[D]')
624
+ b = np.datetime64('NaT', '[D]')
625
+
626
+ # Arrays
627
+ assert_equal(a.astype('M8[s]'), np.array('NaT', dtype='M8[s]'))
628
+ assert_equal(a.astype('M8[ms]'), np.array('NaT', dtype='M8[ms]'))
629
+ assert_equal(a.astype('M8[M]'), np.array('NaT', dtype='M8[M]'))
630
+ assert_equal(a.astype('M8[Y]'), np.array('NaT', dtype='M8[Y]'))
631
+ assert_equal(a.astype('M8[W]'), np.array('NaT', dtype='M8[W]'))
632
+
633
+ # Scalars -> Scalars
634
+ assert_equal(np.datetime64(b, '[s]'), np.datetime64('NaT', '[s]'))
635
+ assert_equal(np.datetime64(b, '[ms]'), np.datetime64('NaT', '[ms]'))
636
+ assert_equal(np.datetime64(b, '[M]'), np.datetime64('NaT', '[M]'))
637
+ assert_equal(np.datetime64(b, '[Y]'), np.datetime64('NaT', '[Y]'))
638
+ assert_equal(np.datetime64(b, '[W]'), np.datetime64('NaT', '[W]'))
639
+
640
+ # Arrays -> Scalars
641
+ assert_equal(np.datetime64(a, '[s]'), np.datetime64('NaT', '[s]'))
642
+ assert_equal(np.datetime64(a, '[ms]'), np.datetime64('NaT', '[ms]'))
643
+ assert_equal(np.datetime64(a, '[M]'), np.datetime64('NaT', '[M]'))
644
+ assert_equal(np.datetime64(a, '[Y]'), np.datetime64('NaT', '[Y]'))
645
+ assert_equal(np.datetime64(a, '[W]'), np.datetime64('NaT', '[W]'))
646
+
647
+ # NaN -> NaT
648
+ nan = np.array([np.nan] * 8 + [0])
649
+ fnan = nan.astype('f')
650
+ lnan = nan.astype('g')
651
+ cnan = nan.astype('D')
652
+ cfnan = nan.astype('F')
653
+ clnan = nan.astype('G')
654
+ hnan = nan.astype(np.half)
655
+
656
+ nat = np.array([np.datetime64('NaT', 's')] * 8 + [np.datetime64(0, 'D')])
657
+ assert_equal(nan.astype('M8[ns]'), nat)
658
+ assert_equal(fnan.astype('M8[ns]'), nat)
659
+ assert_equal(lnan.astype('M8[ns]'), nat)
660
+ assert_equal(cnan.astype('M8[ns]'), nat)
661
+ assert_equal(cfnan.astype('M8[ns]'), nat)
662
+ assert_equal(clnan.astype('M8[ns]'), nat)
663
+ assert_equal(hnan.astype('M8[ns]'), nat)
664
+
665
+ nat = np.array([np.timedelta64('NaT', 'D')] * 8 + [np.timedelta64(0, 's')])
666
+ assert_equal(nan.astype('timedelta64[ns]'), nat)
667
+ assert_equal(fnan.astype('timedelta64[ns]'), nat)
668
+ assert_equal(lnan.astype('timedelta64[ns]'), nat)
669
+ assert_equal(cnan.astype('timedelta64[ns]'), nat)
670
+ assert_equal(cfnan.astype('timedelta64[ns]'), nat)
671
+ assert_equal(clnan.astype('timedelta64[ns]'), nat)
672
+ assert_equal(hnan.astype('timedelta64[ns]'), nat)
673
+
674
+ def test_days_creation(self):
675
+ assert_equal(np.array('1599', dtype='M8[D]').astype('i8'),
676
+ (1600 - 1970) * 365 - (1972 - 1600) / 4 + 3 - 365)
677
+ assert_equal(np.array('1600', dtype='M8[D]').astype('i8'),
678
+ (1600 - 1970) * 365 - (1972 - 1600) / 4 + 3)
679
+ assert_equal(np.array('1601', dtype='M8[D]').astype('i8'),
680
+ (1600 - 1970) * 365 - (1972 - 1600) / 4 + 3 + 366)
681
+ assert_equal(np.array('1900', dtype='M8[D]').astype('i8'),
682
+ (1900 - 1970) * 365 - (1970 - 1900) // 4)
683
+ assert_equal(np.array('1901', dtype='M8[D]').astype('i8'),
684
+ (1900 - 1970) * 365 - (1970 - 1900) // 4 + 365)
685
+ assert_equal(np.array('1967', dtype='M8[D]').astype('i8'), -3 * 365 - 1)
686
+ assert_equal(np.array('1968', dtype='M8[D]').astype('i8'), -2 * 365 - 1)
687
+ assert_equal(np.array('1969', dtype='M8[D]').astype('i8'), -1 * 365)
688
+ assert_equal(np.array('1970', dtype='M8[D]').astype('i8'), 0 * 365)
689
+ assert_equal(np.array('1971', dtype='M8[D]').astype('i8'), 1 * 365)
690
+ assert_equal(np.array('1972', dtype='M8[D]').astype('i8'), 2 * 365)
691
+ assert_equal(np.array('1973', dtype='M8[D]').astype('i8'), 3 * 365 + 1)
692
+ assert_equal(np.array('1974', dtype='M8[D]').astype('i8'), 4 * 365 + 1)
693
+ assert_equal(np.array('2000', dtype='M8[D]').astype('i8'),
694
+ (2000 - 1970) * 365 + (2000 - 1972) // 4)
695
+ assert_equal(np.array('2001', dtype='M8[D]').astype('i8'),
696
+ (2000 - 1970) * 365 + (2000 - 1972) // 4 + 366)
697
+ assert_equal(np.array('2400', dtype='M8[D]').astype('i8'),
698
+ (2400 - 1970) * 365 + (2400 - 1972) // 4 - 3)
699
+ assert_equal(np.array('2401', dtype='M8[D]').astype('i8'),
700
+ (2400 - 1970) * 365 + (2400 - 1972) // 4 - 3 + 366)
701
+
702
+ assert_equal(np.array('1600-02-29', dtype='M8[D]').astype('i8'),
703
+ (1600 - 1970) * 365 - (1972 - 1600) // 4 + 3 + 31 + 28)
704
+ assert_equal(np.array('1600-03-01', dtype='M8[D]').astype('i8'),
705
+ (1600 - 1970) * 365 - (1972 - 1600) // 4 + 3 + 31 + 29)
706
+ assert_equal(np.array('2000-02-29', dtype='M8[D]').astype('i8'),
707
+ (2000 - 1970) * 365 + (2000 - 1972) // 4 + 31 + 28)
708
+ assert_equal(np.array('2000-03-01', dtype='M8[D]').astype('i8'),
709
+ (2000 - 1970) * 365 + (2000 - 1972) // 4 + 31 + 29)
710
+ assert_equal(np.array('2001-03-22', dtype='M8[D]').astype('i8'),
711
+ (2000 - 1970) * 365 + (2000 - 1972) // 4 + 366 + 31 + 28 + 21)
712
+
713
+ def test_days_to_pydate(self):
714
+ assert_equal(np.array('1599', dtype='M8[D]').astype('O'),
715
+ datetime.date(1599, 1, 1))
716
+ assert_equal(np.array('1600', dtype='M8[D]').astype('O'),
717
+ datetime.date(1600, 1, 1))
718
+ assert_equal(np.array('1601', dtype='M8[D]').astype('O'),
719
+ datetime.date(1601, 1, 1))
720
+ assert_equal(np.array('1900', dtype='M8[D]').astype('O'),
721
+ datetime.date(1900, 1, 1))
722
+ assert_equal(np.array('1901', dtype='M8[D]').astype('O'),
723
+ datetime.date(1901, 1, 1))
724
+ assert_equal(np.array('2000', dtype='M8[D]').astype('O'),
725
+ datetime.date(2000, 1, 1))
726
+ assert_equal(np.array('2001', dtype='M8[D]').astype('O'),
727
+ datetime.date(2001, 1, 1))
728
+ assert_equal(np.array('1600-02-29', dtype='M8[D]').astype('O'),
729
+ datetime.date(1600, 2, 29))
730
+ assert_equal(np.array('1600-03-01', dtype='M8[D]').astype('O'),
731
+ datetime.date(1600, 3, 1))
732
+ assert_equal(np.array('2001-03-22', dtype='M8[D]').astype('O'),
733
+ datetime.date(2001, 3, 22))
734
+
735
+ def test_dtype_comparison(self):
736
+ assert_(not (np.dtype('M8[us]') == np.dtype('M8[ms]')))
737
+ assert_(np.dtype('M8[us]') != np.dtype('M8[ms]'))
738
+ assert_(np.dtype('M8[2D]') != np.dtype('M8[D]'))
739
+ assert_(np.dtype('M8[D]') != np.dtype('M8[2D]'))
740
+
741
+ def test_pydatetime_creation(self):
742
+ a = np.array(['1960-03-12', datetime.date(1960, 3, 12)], dtype='M8[D]')
743
+ assert_equal(a[0], a[1])
744
+ a = np.array(['1999-12-31', datetime.date(1999, 12, 31)], dtype='M8[D]')
745
+ assert_equal(a[0], a[1])
746
+ a = np.array(['2000-01-01', datetime.date(2000, 1, 1)], dtype='M8[D]')
747
+ assert_equal(a[0], a[1])
748
+ # Will fail if the date changes during the exact right moment
749
+ a = np.array(['today', datetime.date.today()], dtype='M8[D]')
750
+ assert_equal(a[0], a[1])
751
+ # datetime.datetime.now() returns local time, not UTC
752
+ #a = np.array(['now', datetime.datetime.now()], dtype='M8[s]')
753
+ #assert_equal(a[0], a[1])
754
+
755
+ # we can give a datetime.date time units
756
+ assert_equal(np.array(datetime.date(1960, 3, 12), dtype='M8[s]'),
757
+ np.array(np.datetime64('1960-03-12T00:00:00')))
758
+
759
+ def test_datetime_string_conversion(self):
760
+ a = ['2011-03-16', '1920-01-01', '2013-05-19']
761
+ str_a = np.array(a, dtype='S')
762
+ uni_a = np.array(a, dtype='U')
763
+ dt_a = np.array(a, dtype='M')
764
+
765
+ # String to datetime
766
+ assert_equal(dt_a, str_a.astype('M'))
767
+ assert_equal(dt_a.dtype, str_a.astype('M').dtype)
768
+ dt_b = np.empty_like(dt_a)
769
+ dt_b[...] = str_a
770
+ assert_equal(dt_a, dt_b)
771
+
772
+ # Datetime to string
773
+ assert_equal(str_a, dt_a.astype('S0'))
774
+ str_b = np.empty_like(str_a)
775
+ str_b[...] = dt_a
776
+ assert_equal(str_a, str_b)
777
+
778
+ # Unicode to datetime
779
+ assert_equal(dt_a, uni_a.astype('M'))
780
+ assert_equal(dt_a.dtype, uni_a.astype('M').dtype)
781
+ dt_b = np.empty_like(dt_a)
782
+ dt_b[...] = uni_a
783
+ assert_equal(dt_a, dt_b)
784
+
785
+ # Datetime to unicode
786
+ assert_equal(uni_a, dt_a.astype('U'))
787
+ uni_b = np.empty_like(uni_a)
788
+ uni_b[...] = dt_a
789
+ assert_equal(uni_a, uni_b)
790
+
791
+ # Datetime to long string - gh-9712
792
+ assert_equal(str_a, dt_a.astype((np.bytes_, 128)))
793
+ str_b = np.empty(str_a.shape, dtype=(np.bytes_, 128))
794
+ str_b[...] = dt_a
795
+ assert_equal(str_a, str_b)
796
+
797
+ @pytest.mark.parametrize("time_dtype", ["m8[D]", "M8[Y]"])
798
+ def test_time_byteswapping(self, time_dtype):
799
+ times = np.array(["2017", "NaT"], dtype=time_dtype)
800
+ times_swapped = times.astype(times.dtype.newbyteorder())
801
+ assert_array_equal(times, times_swapped)
802
+
803
+ unswapped = times_swapped.view(np.dtype("int64").newbyteorder())
804
+ assert_array_equal(unswapped, times.view(np.int64))
805
+
806
+ @pytest.mark.parametrize(["time1", "time2"],
807
+ [("M8[s]", "M8[D]"), ("m8[s]", "m8[ns]")])
808
+ def test_time_byteswapped_cast(self, time1, time2):
809
+ dtype1 = np.dtype(time1)
810
+ dtype2 = np.dtype(time2)
811
+ times = np.array(["2017", "NaT"], dtype=dtype1)
812
+ expected = times.astype(dtype2)
813
+
814
+ # Test that every byte-swapping combination also returns the same
815
+ # results (previous tests check that this comparison works fine).
816
+ res = times.astype(dtype1.newbyteorder()).astype(dtype2)
817
+ assert_array_equal(res, expected)
818
+ res = times.astype(dtype2.newbyteorder())
819
+ assert_array_equal(res, expected)
820
+ res = times.astype(dtype1.newbyteorder()).astype(dtype2.newbyteorder())
821
+ assert_array_equal(res, expected)
822
+
823
+ @pytest.mark.parametrize("time_dtype", ["m8[D]", "M8[Y]"])
824
+ @pytest.mark.parametrize("str_dtype", ["U", "S"])
825
+ def test_datetime_conversions_byteorders(self, str_dtype, time_dtype):
826
+ times = np.array(["2017", "NaT"], dtype=time_dtype)
827
+ # Unfortunately, timedelta does not roundtrip:
828
+ from_strings = np.array(["2017", "NaT"], dtype=str_dtype)
829
+ to_strings = times.astype(str_dtype) # assume this is correct
830
+
831
+ # Check that conversion from times to string works if src is swapped:
832
+ times_swapped = times.astype(times.dtype.newbyteorder())
833
+ res = times_swapped.astype(str_dtype)
834
+ assert_array_equal(res, to_strings)
835
+ # And also if both are swapped:
836
+ res = times_swapped.astype(to_strings.dtype.newbyteorder())
837
+ assert_array_equal(res, to_strings)
838
+ # only destination is swapped:
839
+ res = times.astype(to_strings.dtype.newbyteorder())
840
+ assert_array_equal(res, to_strings)
841
+
842
+ # Check that conversion from string to times works if src is swapped:
843
+ from_strings_swapped = from_strings.astype(
844
+ from_strings.dtype.newbyteorder())
845
+ res = from_strings_swapped.astype(time_dtype)
846
+ assert_array_equal(res, times)
847
+ # And if both are swapped:
848
+ res = from_strings_swapped.astype(times.dtype.newbyteorder())
849
+ assert_array_equal(res, times)
850
+ # Only destination is swapped:
851
+ res = from_strings.astype(times.dtype.newbyteorder())
852
+ assert_array_equal(res, times)
853
+
854
+ def test_datetime_array_str(self):
855
+ a = np.array(['2011-03-16', '1920-01-01', '2013-05-19'], dtype='M')
856
+ assert_equal(str(a), "['2011-03-16' '1920-01-01' '2013-05-19']")
857
+
858
+ a = np.array(['2011-03-16T13:55', '1920-01-01T03:12'], dtype='M')
859
+ assert_equal(np.array2string(a, separator=', ',
860
+ formatter={'datetime': lambda x:
861
+ f"'{np.datetime_as_string(x, timezone='UTC')}'"}),
862
+ "['2011-03-16T13:55Z', '1920-01-01T03:12Z']")
863
+
864
+ # Check that one NaT doesn't corrupt subsequent entries
865
+ a = np.array(['2010', 'NaT', '2030']).astype('M')
866
+ assert_equal(str(a), "['2010' 'NaT' '2030']")
867
+
868
+ def test_timedelta_array_str(self):
869
+ a = np.array([-1, 0, 100], dtype='m8[s]')
870
+ assert_equal(str(a), "[ -1 0 100]")
871
+ a = np.array(['NaT', 'NaT'], dtype='m8[ns]')
872
+ assert_equal(str(a), "['NaT' 'NaT']")
873
+ # Check right-alignment with NaTs
874
+ a = np.array([-1, 'NaT', 0], dtype='m8[s]')
875
+ assert_equal(str(a), "[ -1 'NaT' 0]")
876
+ a = np.array([-1, 'NaT', 1234567], dtype='m8[ns]')
877
+ assert_equal(str(a), "[ -1 'NaT' 1234567]")
878
+
879
+ # Test with other byteorder:
880
+ a = np.array([-1, 'NaT', 1234567], dtype='>m8[s]')
881
+ assert_equal(str(a), "[ -1 'NaT' 1234567]")
882
+ a = np.array([-1, 'NaT', 1234567], dtype='<m8[ns]')
883
+ assert_equal(str(a), "[ -1 'NaT' 1234567]")
884
+
885
+ def test_timedelta_array_with_nats(self):
886
+ # Regression test for gh-29497.
887
+ with pytest.warns(
888
+ DeprecationWarning,
889
+ match=self.generic_unit_deprecation_message,
890
+ ):
891
+ x = np.array(
892
+ [
893
+ np.timedelta64("nat"),
894
+ np.timedelta64("nat", "s"),
895
+ np.timedelta64("nat", "ms"),
896
+ np.timedelta64(123, "ms"),
897
+ ]
898
+ )
899
+ for td in x[:3]:
900
+ assert np.isnat(td)
901
+
902
+ def test_timedelta_array_nat_assignment(self):
903
+ # Regression test for gh-29497.
904
+ x = np.zeros(3, dtype='m8[ms]')
905
+ x[1] = np.timedelta64('nat', 's')
906
+ assert np.isnat(x[1])
907
+
908
+ def test_pickle(self):
909
+ # Check that pickle roundtripping works
910
+ for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
911
+ dt = np.dtype('M8[7D]')
912
+ assert_equal(pickle.loads(pickle.dumps(dt, protocol=proto)), dt)
913
+ dt = np.dtype('M8[W]')
914
+ assert_equal(pickle.loads(pickle.dumps(dt, protocol=proto)), dt)
915
+ scalar = np.datetime64('2016-01-01T00:00:00.000000000')
916
+ assert_equal(pickle.loads(pickle.dumps(scalar, protocol=proto)),
917
+ scalar)
918
+ delta = scalar - np.datetime64('2015-01-01T00:00:00.000000000')
919
+ assert_equal(pickle.loads(pickle.dumps(delta, protocol=proto)),
920
+ delta)
921
+
922
+ # Check that loading pickles from 1.6 works
923
+ pkl = b"cnumpy\ndtype\np0\n(S'M8'\np1\nI0\nI1\ntp2\nRp3\n"\
924
+ b"(I4\nS'<'\np4\nNNNI-1\nI-1\nI0\n((dp5\n(S'D'\np6\n"\
925
+ b"I7\nI1\nI1\ntp7\ntp8\ntp9\nb."
926
+ assert_equal(pickle.loads(pkl), np.dtype('<M8[7D]'))
927
+ pkl = b"cnumpy\ndtype\np0\n(S'M8'\np1\nI0\nI1\ntp2\nRp3\n"\
928
+ b"(I4\nS'<'\np4\nNNNI-1\nI-1\nI0\n((dp5\n(S'W'\np6\n"\
929
+ b"I1\nI1\nI1\ntp7\ntp8\ntp9\nb."
930
+ assert_equal(pickle.loads(pkl), np.dtype('<M8[W]'))
931
+ pkl = b"cnumpy\ndtype\np0\n(S'M8'\np1\nI0\nI1\ntp2\nRp3\n"\
932
+ b"(I4\nS'>'\np4\nNNNI-1\nI-1\nI0\n((dp5\n(S'us'\np6\n"\
933
+ b"I1\nI1\nI1\ntp7\ntp8\ntp9\nb."
934
+ assert_equal(pickle.loads(pkl), np.dtype('>M8[us]'))
935
+
936
+ def test_gh_29555(self):
937
+ # check that dtype metadata round-trips when none
938
+ dt = np.dtype('>M8[us]')
939
+ assert dt.metadata is None
940
+ for proto in range(2, pickle.HIGHEST_PROTOCOL + 1):
941
+ res = pickle.loads(pickle.dumps(dt, protocol=proto))
942
+ assert_equal(res, dt)
943
+ assert res.metadata is None
944
+
945
+ def test_setstate(self):
946
+ "Verify that datetime dtype __setstate__ can handle bad arguments"
947
+ dt = np.dtype('>M8[us]')
948
+ assert_raises(ValueError, dt.__setstate__,
949
+ (4, '>', None, None, None, -1, -1, 0, 1))
950
+ assert_(dt.__reduce__()[2] == np.dtype('>M8[us]').__reduce__()[2])
951
+ assert_raises(TypeError, dt.__setstate__,
952
+ (4, '>', None, None, None, -1, -1, 0, ({}, 'xxx')))
953
+ assert_(dt.__reduce__()[2] == np.dtype('>M8[us]').__reduce__()[2])
954
+
955
+ def test_dtype_promotion(self):
956
+ # datetime <op> datetime computes the metadata gcd
957
+ # timedelta <op> timedelta computes the metadata gcd
958
+ for mM in ['m', 'M']:
959
+ assert_equal(
960
+ np.promote_types(np.dtype(mM + '8[2Y]'), np.dtype(mM + '8[2Y]')),
961
+ np.dtype(mM + '8[2Y]'))
962
+ assert_equal(
963
+ np.promote_types(np.dtype(mM + '8[12Y]'), np.dtype(mM + '8[15Y]')),
964
+ np.dtype(mM + '8[3Y]'))
965
+ assert_equal(
966
+ np.promote_types(np.dtype(mM + '8[62M]'), np.dtype(mM + '8[24M]')),
967
+ np.dtype(mM + '8[2M]'))
968
+ assert_equal(
969
+ np.promote_types(np.dtype(mM + '8[1W]'), np.dtype(mM + '8[2D]')),
970
+ np.dtype(mM + '8[1D]'))
971
+ assert_equal(
972
+ np.promote_types(np.dtype(mM + '8[W]'), np.dtype(mM + '8[13s]')),
973
+ np.dtype(mM + '8[s]'))
974
+ assert_equal(
975
+ np.promote_types(np.dtype(mM + '8[13W]'), np.dtype(mM + '8[49s]')),
976
+ np.dtype(mM + '8[7s]'))
977
+ # timedelta <op> timedelta raises when there is no reasonable gcd
978
+ assert_raises(TypeError, np.promote_types,
979
+ np.dtype('m8[Y]'), np.dtype('m8[D]'))
980
+ assert_raises(TypeError, np.promote_types,
981
+ np.dtype('m8[M]'), np.dtype('m8[W]'))
982
+ # timedelta and float cannot be safely cast with each other
983
+ assert_raises(TypeError, np.promote_types, "float32", "m8")
984
+ assert_raises(TypeError, np.promote_types, "m8", "float32")
985
+ assert_raises(TypeError, np.promote_types, "uint64", "m8")
986
+ assert_raises(TypeError, np.promote_types, "m8", "uint64")
987
+
988
+ # timedelta <op> timedelta may overflow with big unit ranges
989
+ assert_raises(OverflowError, np.promote_types,
990
+ np.dtype('m8[W]'), np.dtype('m8[fs]'))
991
+ assert_raises(OverflowError, np.promote_types,
992
+ np.dtype('m8[s]'), np.dtype('m8[as]'))
993
+
994
+ def test_cast_overflow(self):
995
+ # gh-4486
996
+ def cast():
997
+ numpy.datetime64("1971-01-01 00:00:00.000000000000000").astype("<M8[D]")
998
+ assert_raises(OverflowError, cast)
999
+
1000
+ def cast2():
1001
+ numpy.datetime64("2014").astype("<M8[fs]")
1002
+ assert_raises(OverflowError, cast2)
1003
+
1004
+ def test_cast_overflow_safe_unit_conversion(self):
1005
+ # Overflow when converting datetime64 between linear units
1006
+ # (the fast-path cast), e.g. seconds -> nanoseconds.
1007
+ # INT64_MAX / 1e9 ≈ 9.2e9 seconds ≈ 292 years from epoch,
1008
+ # so dates beyond ~2262 overflow when cast to ns.
1009
+
1010
+ # gh-16352: upconversion to finer units overflows
1011
+ arr = np.array(["2367-12-31 12:00:00"], dtype="datetime64[h]")
1012
+ with pytest.raises(OverflowError, match="Overflow"):
1013
+ arr.astype("datetime64[ns]")
1014
+
1015
+ # gh-16352: scalar case
1016
+ val = np.datetime64("3000-01-01", "s")
1017
+ with pytest.raises(OverflowError, match="Overflow"):
1018
+ val.astype("datetime64[ns]")
1019
+
1020
+ # gh-22346: downconversion to coarser units overflows near INT64_MIN
1021
+ dt = np.datetime64(np.iinfo(np.int64).min + 1, "s")
1022
+ with pytest.raises(OverflowError, match="Overflow"):
1023
+ dt.astype("M8[m]")
1024
+
1025
+ # negative overflow (far in the past)
1026
+ val_neg = np.datetime64("0001-01-01", "s")
1027
+ with pytest.raises(OverflowError, match="Overflow"):
1028
+ val_neg.astype("datetime64[ns]")
1029
+
1030
+ # timedelta overflow (strided cast path in dtype_transfer.c)
1031
+ td = np.timedelta64(2**62, "s")
1032
+ with pytest.raises(OverflowError, match="Overflow"):
1033
+ td.astype("timedelta64[ns]")
1034
+
1035
+ # timedelta overflow (scalar cast path in datetime.c via
1036
+ # cast_timedelta_to_timedelta)
1037
+ td_big = np.timedelta64(2**62, "s")
1038
+ with pytest.raises(OverflowError, match="Overflow"):
1039
+ np.array(td_big, dtype="timedelta64[ns]")
1040
+
1041
+ # timedelta exact boundary: INT64_MAX // 1e9 = 9223372036
1042
+ td_ok = np.timedelta64(9223372036, "s")
1043
+ result_td = td_ok.astype("timedelta64[ns]")
1044
+ assert result_td == np.timedelta64(9223372036000000000, "ns")
1045
+
1046
+ td_bad = np.timedelta64(9223372037, "s")
1047
+ with pytest.raises(OverflowError, match="Overflow"):
1048
+ td_bad.astype("timedelta64[ns]")
1049
+
1050
+ # negative timedelta overflow
1051
+ td_neg = np.timedelta64(-9223372037, "s")
1052
+ with pytest.raises(OverflowError, match="Overflow"):
1053
+ td_neg.astype("timedelta64[ns]")
1054
+
1055
+ # timedelta NaT passthrough
1056
+ td_nat = np.timedelta64("NaT", "s")
1057
+ result_td_nat = td_nat.astype("timedelta64[ns]")
1058
+ assert np.isnat(result_td_nat)
1059
+
1060
+ # valid conversions near the boundary should still work
1061
+ val_ok = np.datetime64("2020-01-01", "s")
1062
+ result = val_ok.astype("datetime64[ns]")
1063
+ assert result == np.datetime64("2020-01-01", "ns")
1064
+
1065
+ arr_ok = np.array(["2000-01-01", "2020-06-15"], dtype="datetime64[s]")
1066
+ result_arr = arr_ok.astype("datetime64[ns]")
1067
+ expected = np.array(["2000-01-01", "2020-06-15"], dtype="datetime64[ns]")
1068
+ assert_equal(result_arr, expected)
1069
+
1070
+ # NaT should pass through without raising
1071
+ arr_nat = np.array(["NaT", "2020-01-01"], dtype="datetime64[s]")
1072
+ result_nat = arr_nat.astype("datetime64[ns]")
1073
+ assert np.isnat(result_nat[0])
1074
+ assert result_nat[1] == np.datetime64("2020-01-01", "ns")
1075
+
1076
+ # Exact boundary: INT64_MAX // 1e9 = 9223372036 seconds is OK,
1077
+ # 9223372037 seconds overflows when cast to ns.
1078
+ ok_boundary = np.datetime64(9223372036, "s")
1079
+ result_boundary = ok_boundary.astype("datetime64[ns]")
1080
+ assert result_boundary == np.datetime64(9223372036, "s")
1081
+
1082
+ bad_boundary = np.datetime64(9223372037, "s")
1083
+ with pytest.raises(OverflowError, match="Overflow"):
1084
+ bad_boundary.astype("datetime64[ns]")
1085
+
1086
+ # Exercise the num != 1 code path (e.g. "2s" metadata)
1087
+ arr_2s = np.array([3], dtype="datetime64[2s]")
1088
+ result_2s = arr_2s.astype("datetime64[s]")
1089
+ assert result_2s[0] == np.datetime64(6, "s")
1090
+
1091
+ # Overflow with num != 1
1092
+ arr_2s_big = np.array([np.iinfo(np.int64).max // 2], dtype="datetime64[2s]")
1093
+ with pytest.raises(OverflowError, match="Overflow"):
1094
+ arr_2s_big.astype("datetime64[ns]")
1095
+
1096
+ def test_arithmetic_overflow_raises_add_sub(self):
1097
+ # Add/sub on datetime64/timedelta64 must raise OverflowError instead
1098
+ # of silently wrapping past INT64 range. Covers all six loops:
1099
+ # Mm_M_add, mM_M_add, mm_m_add, Mm_M_subtract, MM_m_subtract,
1100
+ # mm_m_subtract. Each loop is exercised both via the scalar fast
1101
+ # path and via the strided ufunc loop.
1102
+ big = np.iinfo(np.int64).max
1103
+ dt_pos = np.datetime64(big - 1, "s")
1104
+ dt_neg = np.datetime64(-big + 1, "s")
1105
+ td_pos = np.timedelta64(2, "s")
1106
+ td_big = np.timedelta64(big - 1, "s")
1107
+ td_neg = np.timedelta64(-big + 1, "s")
1108
+
1109
+ # datetime64 + timedelta64 (both operand orders)
1110
+ with pytest.raises(OverflowError, match="Overflow"):
1111
+ dt_pos + td_pos
1112
+ with pytest.raises(OverflowError, match="Overflow"):
1113
+ td_pos + dt_pos
1114
+
1115
+ # datetime64 - timedelta64
1116
+ with pytest.raises(OverflowError, match="Overflow"):
1117
+ dt_neg - td_pos
1118
+
1119
+ # datetime64 - datetime64 (result is timedelta64)
1120
+ with pytest.raises(OverflowError, match="Overflow"):
1121
+ np.datetime64(big, "s") - dt_neg
1122
+
1123
+ # timedelta64 + timedelta64
1124
+ with pytest.raises(OverflowError, match="Overflow"):
1125
+ td_big + td_pos
1126
+
1127
+ # timedelta64 - timedelta64
1128
+ with pytest.raises(OverflowError, match="Overflow"):
1129
+ td_neg - td_pos
1130
+
1131
+ # Overflow that does *not* wrap onto NPY_DATETIME_NAT -- isolates
1132
+ # the safe_add bounds check from the result == NaT short-circuit.
1133
+ # big + 2 wraps to INT64_MIN + 1, a valid timedelta value.
1134
+ with pytest.raises(OverflowError, match="Overflow"):
1135
+ np.timedelta64(big, "s") + np.timedelta64(2, "s")
1136
+ # Negative-side branch of safe_add: a < 0 && b < INT64_MIN - a.
1137
+ # -big + -2 wraps to INT64_MAX - 1, also non-NaT.
1138
+ with pytest.raises(OverflowError, match="Overflow"):
1139
+ np.timedelta64(-big, "s") + np.timedelta64(-2, "s")
1140
+
1141
+ # Array path -- one case per loop so the strided ufunc kernel is
1142
+ # exercised for every signature, not only mm_m_add/subtract.
1143
+ arr_td = np.array([0, big - 1, -big + 1], dtype="timedelta64[s]")
1144
+ # TIMEDELTA_mm_m_add, TIMEDELTA_mm_m_subtract
1145
+ with pytest.raises(OverflowError, match="Overflow"):
1146
+ arr_td + td_pos
1147
+ with pytest.raises(OverflowError, match="Overflow"):
1148
+ arr_td - td_pos
1149
+ # DATETIME_Mm_M_add (datetime + timedelta)
1150
+ arr_dt = np.array([0, big - 1], dtype="datetime64[s]")
1151
+ arr_td_add = np.array([0, 2], dtype="timedelta64[s]")
1152
+ with pytest.raises(OverflowError, match="Overflow"):
1153
+ arr_dt + arr_td_add
1154
+ # DATETIME_mM_M_add (timedelta + datetime, swapped operand order)
1155
+ with pytest.raises(OverflowError, match="Overflow"):
1156
+ arr_td_add + arr_dt
1157
+ # DATETIME_Mm_M_subtract (datetime - timedelta)
1158
+ arr_dt_neg = np.array([0, -big + 1], dtype="datetime64[s]")
1159
+ with pytest.raises(OverflowError, match="Overflow"):
1160
+ arr_dt_neg - arr_td_add
1161
+ # DATETIME_MM_m_subtract (datetime - datetime, result timedelta)
1162
+ arr_dt_big = np.array([0, big], dtype="datetime64[s]")
1163
+ with pytest.raises(OverflowError, match="Overflow"):
1164
+ arr_dt_big - arr_dt_neg
1165
+
1166
+ def test_arithmetic_overflow_raises_multiply(self):
1167
+ # Integer multiplication of timedelta64 must raise OverflowError on
1168
+ # signed-integer overflow. Covers TIMEDELTA_mq_m_multiply and
1169
+ # TIMEDELTA_qm_m_multiply.
1170
+ big = np.iinfo(np.int64).max
1171
+ int64_min = np.iinfo(np.int64).min
1172
+ td = np.timedelta64(big // 2 + 1, "s")
1173
+
1174
+ with pytest.raises(OverflowError, match="Overflow"):
1175
+ td * np.int64(2)
1176
+ with pytest.raises(OverflowError, match="Overflow"):
1177
+ np.int64(2) * td
1178
+
1179
+ # Overflow that does *not* wrap onto NPY_DATETIME_NAT -- isolates
1180
+ # the safe_mul bounds check from the result == NaT short-circuit.
1181
+ # big * 2 wraps to -2, a valid (non-NaT) timedelta.
1182
+ with pytest.raises(OverflowError, match="Overflow"):
1183
+ np.timedelta64(big, "s") * np.int64(2)
1184
+ # Negative multiplier branch of safe_mul.
1185
+ with pytest.raises(OverflowError, match="Overflow"):
1186
+ np.timedelta64(big, "s") * np.int64(-2)
1187
+ # INT64_MIN multiplier exercises the b < 0 sub-branch and is
1188
+ # itself the NaT sentinel; the bounds check must catch it before
1189
+ # the multiply produces a UB-tainted value.
1190
+ with pytest.raises(OverflowError, match="Overflow"):
1191
+ np.timedelta64(2, "s") * np.int64(int64_min)
1192
+
1193
+ # Array path -- one case per loop signature.
1194
+ arr = np.array([1, big // 2 + 1], dtype="timedelta64[s]")
1195
+ # TIMEDELTA_mq_m_multiply (timedelta * int64)
1196
+ with pytest.raises(OverflowError, match="Overflow"):
1197
+ arr * np.int64(2)
1198
+ # TIMEDELTA_qm_m_multiply (int64 * timedelta), reversed operand
1199
+ # order to select the qm signature.
1200
+ with pytest.raises(OverflowError, match="Overflow"):
1201
+ np.int64(2) * arr
1202
+
1203
+ def test_arithmetic_result_equals_nat_raises(self):
1204
+ # NPY_DATETIME_NAT == INT64_MIN. An arithmetic result that lands
1205
+ # exactly on INT64_MIN would be silently misinterpreted as NaT, so
1206
+ # it must raise instead.
1207
+ big = np.iinfo(np.int64).max
1208
+
1209
+ # add: (-big) + (-1) == INT64_MIN
1210
+ with pytest.raises(OverflowError, match="Overflow"):
1211
+ np.timedelta64(-big, "s") + np.timedelta64(-1, "s")
1212
+ # sub: (-big) - 1 == INT64_MIN
1213
+ with pytest.raises(OverflowError, match="Overflow"):
1214
+ np.timedelta64(-big, "s") - np.timedelta64(1, "s")
1215
+ # mul: (-2**62) * 2 == INT64_MIN
1216
+ with pytest.raises(OverflowError, match="Overflow"):
1217
+ np.timedelta64(-(1 << 62), "s") * np.int64(2)
1218
+
1219
+ # Same check via the strided ufunc loop -- the second element
1220
+ # (-big + -1) == INT64_MIN.
1221
+ arr = np.array([0, -big], dtype="timedelta64[s]")
1222
+ with pytest.raises(OverflowError, match="Overflow"):
1223
+ arr + np.timedelta64(-1, "s")
1224
+
1225
+ def test_arithmetic_nat_propagation(self):
1226
+ # NaT inputs must pass through every datetime/timedelta arithmetic
1227
+ # ufunc without raising, even now that overflow checking is on.
1228
+ dt = np.datetime64(0, "s")
1229
+ td = np.timedelta64(2, "s")
1230
+ nat_dt = np.datetime64("NaT", "s")
1231
+ nat_td = np.timedelta64("NaT", "s")
1232
+ big = np.iinfo(np.int64).max
1233
+
1234
+ # add/sub
1235
+ assert np.isnat(nat_dt + td)
1236
+ assert np.isnat(td + nat_dt)
1237
+ assert np.isnat(dt + nat_td)
1238
+ assert np.isnat(nat_dt - td)
1239
+ assert np.isnat(nat_dt - dt)
1240
+ assert np.isnat(nat_td + td)
1241
+ assert np.isnat(nat_td - td)
1242
+
1243
+ # multiply
1244
+ assert np.isnat(nat_td * np.int64(5))
1245
+ assert np.isnat(np.int64(5) * nat_td)
1246
+
1247
+ # Regression guard: the NaT short-circuit must run before the
1248
+ # overflow check, so a NaT operand combined with a value that
1249
+ # would otherwise overflow still yields NaT instead of raising.
1250
+ assert np.isnat(nat_dt + np.timedelta64(big, "s"))
1251
+ assert np.isnat(np.timedelta64(big, "s") + nat_td)
1252
+ assert np.isnat(nat_td * np.int64(big))
1253
+
1254
+ def test_arithmetic_valid_boundary(self):
1255
+ # Regression guard: overflow checks must not be too aggressive --
1256
+ # values that just barely fit must continue to work.
1257
+ big = np.iinfo(np.int64).max
1258
+
1259
+ ok_dt = np.datetime64(big - 1, "s") + np.timedelta64(1, "s")
1260
+ assert ok_dt == np.datetime64(big, "s")
1261
+ ok_td = np.timedelta64(big - 1, "s") + np.timedelta64(1, "s")
1262
+ assert ok_td == np.timedelta64(big, "s")
1263
+
1264
+ small = np.timedelta64(3, "s")
1265
+ assert small * np.int64(7) == np.timedelta64(21, "s")
1266
+ assert np.int64(7) * small == np.timedelta64(21, "s")
1267
+
1268
+ def test_datetime64_item_int64_min_edge_case(self):
1269
+ info = np.iinfo(np.int64)
1270
+
1271
+ for offset in [1, 2, 100, 1000, 10000]:
1272
+ dt64 = np.datetime64(info.min + offset, "D")
1273
+ result = dt64.item()
1274
+ # expected integer value
1275
+ assert result == info.min + offset
1276
+ assert isinstance(result, int)
1277
+
1278
+ def test_pyobject_roundtrip(self):
1279
+ # All datetime types should be able to roundtrip through object
1280
+ a = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0,
1281
+ -1020040340, -2942398, -1, 0, 1, 234523453, 1199164176],
1282
+ dtype=np.int64)
1283
+ # With date units
1284
+ for unit in ['M8[D]', 'M8[W]', 'M8[M]', 'M8[Y]']:
1285
+ b = a.copy().view(dtype=unit)
1286
+ b[0] = '-0001-01-01'
1287
+ b[1] = '-0001-12-31'
1288
+ b[2] = '0000-01-01'
1289
+ b[3] = '0001-01-01'
1290
+ b[4] = '1969-12-31'
1291
+ b[5] = '1970-01-01'
1292
+ b[6] = '9999-12-31'
1293
+ b[7] = '10000-01-01'
1294
+ b[8] = 'NaT'
1295
+
1296
+ assert_equal(b.astype(object).astype(unit), b,
1297
+ f"Error roundtripping unit {unit}")
1298
+ # With time units
1299
+ for unit in ['M8[as]', 'M8[16fs]', 'M8[ps]', 'M8[us]',
1300
+ 'M8[300as]', 'M8[20us]']:
1301
+ b = a.copy().view(dtype=unit)
1302
+ b[0] = '-0001-01-01T00'
1303
+ b[1] = '-0001-12-31T00'
1304
+ b[2] = '0000-01-01T00'
1305
+ b[3] = '0001-01-01T00'
1306
+ b[4] = '1969-12-31T23:59:59.999999'
1307
+ b[5] = '1970-01-01T00'
1308
+ b[6] = '9999-12-31T23:59:59.999999'
1309
+ b[7] = '10000-01-01T00'
1310
+ b[8] = 'NaT'
1311
+
1312
+ assert_equal(b.astype(object).astype(unit), b,
1313
+ f"Error roundtripping unit {unit}")
1314
+
1315
+ def test_month_truncation(self):
1316
+ # Make sure that months are truncating correctly
1317
+ assert_equal(np.array('1945-03-01', dtype='M8[M]'),
1318
+ np.array('1945-03-31', dtype='M8[M]'))
1319
+ assert_equal(np.array('1969-11-01', dtype='M8[M]'),
1320
+ np.array('1969-11-30T23:59:59.99999', dtype='M').astype('M8[M]'))
1321
+ assert_equal(np.array('1969-12-01', dtype='M8[M]'),
1322
+ np.array('1969-12-31T23:59:59.99999', dtype='M').astype('M8[M]'))
1323
+ assert_equal(np.array('1970-01-01', dtype='M8[M]'),
1324
+ np.array('1970-01-31T23:59:59.99999', dtype='M').astype('M8[M]'))
1325
+ assert_equal(np.array('1980-02-01', dtype='M8[M]'),
1326
+ np.array('1980-02-29T23:59:59.99999', dtype='M').astype('M8[M]'))
1327
+
1328
+ def test_different_unit_comparison(self):
1329
+ # Check some years with date units
1330
+ for unit1 in ['Y', 'M', 'D']:
1331
+ dt1 = np.dtype(f'M8[{unit1}]')
1332
+ for unit2 in ['Y', 'M', 'D']:
1333
+ dt2 = np.dtype(f'M8[{unit2}]')
1334
+ assert_equal(np.array('1945', dtype=dt1),
1335
+ np.array('1945', dtype=dt2))
1336
+ assert_equal(np.array('1970', dtype=dt1),
1337
+ np.array('1970', dtype=dt2))
1338
+ assert_equal(np.array('9999', dtype=dt1),
1339
+ np.array('9999', dtype=dt2))
1340
+ assert_equal(np.array('10000', dtype=dt1),
1341
+ np.array('10000-01-01', dtype=dt2))
1342
+ assert_equal(np.datetime64('1945', unit1),
1343
+ np.datetime64('1945', unit2))
1344
+ assert_equal(np.datetime64('1970', unit1),
1345
+ np.datetime64('1970', unit2))
1346
+ assert_equal(np.datetime64('9999', unit1),
1347
+ np.datetime64('9999', unit2))
1348
+ assert_equal(np.datetime64('10000', unit1),
1349
+ np.datetime64('10000-01-01', unit2))
1350
+ # Check some datetimes with time units
1351
+ for unit1 in ['6h', 'h', 'm', 's', '10ms', 'ms', 'us']:
1352
+ dt1 = np.dtype(f'M8[{unit1}]')
1353
+ for unit2 in ['h', 'm', 's', 'ms', 'us']:
1354
+ dt2 = np.dtype(f'M8[{unit2}]')
1355
+ assert_equal(np.array('1945-03-12T18', dtype=dt1),
1356
+ np.array('1945-03-12T18', dtype=dt2))
1357
+ assert_equal(np.array('1970-03-12T18', dtype=dt1),
1358
+ np.array('1970-03-12T18', dtype=dt2))
1359
+ assert_equal(np.array('9999-03-12T18', dtype=dt1),
1360
+ np.array('9999-03-12T18', dtype=dt2))
1361
+ assert_equal(np.array('10000-01-01T00', dtype=dt1),
1362
+ np.array('10000-01-01T00', dtype=dt2))
1363
+ assert_equal(np.datetime64('1945-03-12T18', unit1),
1364
+ np.datetime64('1945-03-12T18', unit2))
1365
+ assert_equal(np.datetime64('1970-03-12T18', unit1),
1366
+ np.datetime64('1970-03-12T18', unit2))
1367
+ assert_equal(np.datetime64('9999-03-12T18', unit1),
1368
+ np.datetime64('9999-03-12T18', unit2))
1369
+ assert_equal(np.datetime64('10000-01-01T00', unit1),
1370
+ np.datetime64('10000-01-01T00', unit2))
1371
+ # Check some days with units that won't overflow
1372
+ for unit1 in ['D', '12h', 'h', 'm', 's', '4s', 'ms', 'us']:
1373
+ dt1 = np.dtype(f'M8[{unit1}]')
1374
+ for unit2 in ['D', 'h', 'm', 's', 'ms', 'us']:
1375
+ dt2 = np.dtype(f'M8[{unit2}]')
1376
+ assert_(np.equal(np.array('1932-02-17', dtype='M').astype(dt1),
1377
+ np.array('1932-02-17T00:00:00', dtype='M').astype(dt2),
1378
+ casting='unsafe'))
1379
+ assert_(np.equal(np.array('10000-04-27', dtype='M').astype(dt1),
1380
+ np.array('10000-04-27T00:00:00', dtype='M').astype(dt2),
1381
+ casting='unsafe'))
1382
+
1383
+ # Shouldn't be able to compare datetime and timedelta
1384
+ a = np.array('2012-12-21', dtype='M8[D]')
1385
+ b = np.array(3, dtype='m8[D]')
1386
+ assert_raises(TypeError, np.less, a, b)
1387
+ # not even if "unsafe"
1388
+ assert_raises(TypeError, np.less, a, b, casting='unsafe')
1389
+
1390
+ def test_datetime_like(self):
1391
+ a = np.array([3], dtype='m8[4D]')
1392
+ b = np.array(['2012-12-21'], dtype='M8[D]')
1393
+
1394
+ assert_equal(np.ones_like(a).dtype, a.dtype)
1395
+ assert_equal(np.zeros_like(a).dtype, a.dtype)
1396
+ assert_equal(np.empty_like(a).dtype, a.dtype)
1397
+ assert_equal(np.ones_like(b).dtype, b.dtype)
1398
+ assert_equal(np.zeros_like(b).dtype, b.dtype)
1399
+ assert_equal(np.empty_like(b).dtype, b.dtype)
1400
+
1401
+ def test_timedelta64_unary(self):
1402
+ for tda, tdb, tdzero in \
1403
+ [
1404
+ # One-dimensional arrays
1405
+ (np.array([3], dtype='m8[D]'),
1406
+ np.array([-3], dtype='m8[D]'),
1407
+ np.array([0], dtype='m8[D]')),
1408
+ # NumPy scalars
1409
+ (np.timedelta64(3, '[D]'),
1410
+ np.timedelta64(-3, '[D]'),
1411
+ np.timedelta64(0, '[D]')),
1412
+ ]:
1413
+ # negative ufunc
1414
+ assert_equal(-tdb, tda)
1415
+ assert_equal((-tdb).dtype, tda.dtype)
1416
+ assert_equal(np.negative(tdb), tda)
1417
+ assert_equal(np.negative(tdb).dtype, tda.dtype)
1418
+
1419
+ # positive ufunc
1420
+ assert_equal(np.positive(tda), tda)
1421
+ assert_equal(np.positive(tda).dtype, tda.dtype)
1422
+ assert_equal(np.positive(tdb), tdb)
1423
+ assert_equal(np.positive(tdb).dtype, tdb.dtype)
1424
+
1425
+ # absolute ufunc
1426
+ assert_equal(np.absolute(tdb), tda)
1427
+ assert_equal(np.absolute(tdb).dtype, tda.dtype)
1428
+
1429
+ # sign ufunc
1430
+ assert_equal(np.sign(tda), np.ones_like(tda, dtype=np.float64),
1431
+ strict=True)
1432
+ assert_equal(np.sign(tdb), -np.ones_like(tdb, dtype=np.float64),
1433
+ strict=True)
1434
+ assert_equal(np.sign(tdzero), np.zeros_like(tdzero, dtype=np.float64),
1435
+ strict=True)
1436
+
1437
+ def test_timedelta64_sign_nat(self):
1438
+ x = np.array([np.timedelta64(-123, 's'),
1439
+ np.timedelta64(0, 's'),
1440
+ np.timedelta64(88, 's'),
1441
+ np.timedelta64('NaT', 's')])
1442
+ s = np.sign(x)
1443
+ assert_equal(s, np.array([-1.0, 0.0, 1.0, np.nan]), strict=True)
1444
+
1445
+ def test_timedelta64_sign_nat_scalar(self):
1446
+ nat = np.timedelta64('nat', 'm')
1447
+ assert_equal(np.sign(nat), np.nan)
1448
+
1449
+ def test_datetime_add(self):
1450
+ for dta, dtb, dtc, dtnat, tda, tdb, tdc in \
1451
+ [
1452
+ # One-dimensional arrays
1453
+ (np.array(['2012-12-21'], dtype='M8[D]'),
1454
+ np.array(['2012-12-24'], dtype='M8[D]'),
1455
+ np.array(['2012-12-21T11'], dtype='M8[h]'),
1456
+ np.array(['NaT'], dtype='M8[D]'),
1457
+ np.array([3], dtype='m8[D]'),
1458
+ np.array([11], dtype='m8[h]'),
1459
+ np.array([3 * 24 + 11], dtype='m8[h]')),
1460
+ # NumPy scalars
1461
+ (np.datetime64('2012-12-21', '[D]'),
1462
+ np.datetime64('2012-12-24', '[D]'),
1463
+ np.datetime64('2012-12-21T11', '[h]'),
1464
+ np.datetime64('NaT', '[D]'),
1465
+ np.timedelta64(3, '[D]'),
1466
+ np.timedelta64(11, '[h]'),
1467
+ np.timedelta64(3 * 24 + 11, '[h]'))]:
1468
+ # m8 + m8
1469
+ assert_equal(tda + tdb, tdc)
1470
+ assert_equal((tda + tdb).dtype, np.dtype('m8[h]'))
1471
+
1472
+ with pytest.warns(
1473
+ DeprecationWarning,
1474
+ match=self.generic_unit_deprecation_message,
1475
+ ):
1476
+ # m8 + bool
1477
+ assert_equal(tdb + True, tdb + 1)
1478
+ assert_equal((tdb + True).dtype, np.dtype('m8[h]'))
1479
+ # m8 + int
1480
+ assert_equal(tdb + 3 * 24, tdc)
1481
+ assert_equal((tdb + 3 * 24).dtype, np.dtype('m8[h]'))
1482
+ # bool + m8
1483
+ assert_equal(False + tdb, tdb)
1484
+ assert_equal((False + tdb).dtype, np.dtype('m8[h]'))
1485
+ # int + m8
1486
+ assert_equal(3 * 24 + tdb, tdc)
1487
+ assert_equal((3 * 24 + tdb).dtype, np.dtype('m8[h]'))
1488
+ # M8 + bool
1489
+ assert_equal(dta + True, dta + 1)
1490
+ assert_equal(dtnat + True, dtnat)
1491
+ assert_equal((dta + True).dtype, np.dtype('M8[D]'))
1492
+ # M8 + int
1493
+ assert_equal(dta + 3, dtb)
1494
+ assert_equal(dtnat + 3, dtnat)
1495
+ assert_equal((dta + 3).dtype, np.dtype('M8[D]'))
1496
+ # bool + M8
1497
+ assert_equal(False + dta, dta)
1498
+ assert_equal(False + dtnat, dtnat)
1499
+ assert_equal((False + dta).dtype, np.dtype('M8[D]'))
1500
+ # int + M8
1501
+ assert_equal(3 + dta, dtb)
1502
+ assert_equal(3 + dtnat, dtnat)
1503
+ assert_equal((3 + dta).dtype, np.dtype('M8[D]'))
1504
+ # M8 + m8
1505
+ assert_equal(dta + tda, dtb)
1506
+ assert_equal(dtnat + tda, dtnat)
1507
+ assert_equal((dta + tda).dtype, np.dtype('M8[D]'))
1508
+ # m8 + M8
1509
+ assert_equal(tda + dta, dtb)
1510
+ assert_equal(tda + dtnat, dtnat)
1511
+ assert_equal((tda + dta).dtype, np.dtype('M8[D]'))
1512
+
1513
+ # In M8 + m8, the result goes to higher precision
1514
+ assert_equal(np.add(dta, tdb, casting='unsafe'), dtc)
1515
+ assert_equal(np.add(dta, tdb, casting='unsafe').dtype,
1516
+ np.dtype('M8[h]'))
1517
+ assert_equal(np.add(tdb, dta, casting='unsafe'), dtc)
1518
+ assert_equal(np.add(tdb, dta, casting='unsafe').dtype,
1519
+ np.dtype('M8[h]'))
1520
+
1521
+ # M8 + M8
1522
+ assert_raises(TypeError, np.add, dta, dtb)
1523
+
1524
+ def test_datetime_subtract(self):
1525
+ for dta, dtb, dtc, dtd, dte, dtnat, tda, tdb, tdc in \
1526
+ [
1527
+ # One-dimensional arrays
1528
+ (np.array(['2012-12-21'], dtype='M8[D]'),
1529
+ np.array(['2012-12-24'], dtype='M8[D]'),
1530
+ np.array(['1940-12-24'], dtype='M8[D]'),
1531
+ np.array(['1940-12-24T00'], dtype='M8[h]'),
1532
+ np.array(['1940-12-23T13'], dtype='M8[h]'),
1533
+ np.array(['NaT'], dtype='M8[D]'),
1534
+ np.array([3], dtype='m8[D]'),
1535
+ np.array([11], dtype='m8[h]'),
1536
+ np.array([3 * 24 - 11], dtype='m8[h]')),
1537
+ # NumPy scalars
1538
+ (np.datetime64('2012-12-21', '[D]'),
1539
+ np.datetime64('2012-12-24', '[D]'),
1540
+ np.datetime64('1940-12-24', '[D]'),
1541
+ np.datetime64('1940-12-24T00', '[h]'),
1542
+ np.datetime64('1940-12-23T13', '[h]'),
1543
+ np.datetime64('NaT', '[D]'),
1544
+ np.timedelta64(3, '[D]'),
1545
+ np.timedelta64(11, '[h]'),
1546
+ np.timedelta64(3 * 24 - 11, '[h]'))]:
1547
+ # m8 - m8
1548
+ assert_equal(tda - tdb, tdc)
1549
+ assert_equal((tda - tdb).dtype, np.dtype('m8[h]'))
1550
+ assert_equal(tdb - tda, -tdc)
1551
+ assert_equal((tdb - tda).dtype, np.dtype("m8[h]"))
1552
+ with pytest.warns(
1553
+ DeprecationWarning,
1554
+ match=self.generic_unit_deprecation_message,
1555
+ ):
1556
+ # m8 - bool
1557
+ assert_equal(tdc - True, tdc - 1)
1558
+ assert_equal((tdc - True).dtype, np.dtype('m8[h]'))
1559
+ # m8 - int
1560
+ assert_equal(tdc - 3 * 24, -tdb)
1561
+ assert_equal((tdc - 3 * 24).dtype, np.dtype('m8[h]'))
1562
+ # int - m8
1563
+ assert_equal(False - tdb, -tdb)
1564
+ assert_equal((False - tdb).dtype, np.dtype('m8[h]'))
1565
+ # int - m8
1566
+ assert_equal(3 * 24 - tdb, tdc)
1567
+ assert_equal((3 * 24 - tdb).dtype, np.dtype('m8[h]'))
1568
+ # M8 - bool
1569
+ assert_equal(dtb - True, dtb - 1)
1570
+ assert_equal(dtnat - True, dtnat)
1571
+ assert_equal((dtb - True).dtype, np.dtype('M8[D]'))
1572
+ # M8 - int
1573
+ assert_equal(dtb - 3, dta)
1574
+ assert_equal(dtnat - 3, dtnat)
1575
+ assert_equal((dtb - 3).dtype, np.dtype('M8[D]'))
1576
+ # M8 - m8
1577
+ assert_equal(dtb - tda, dta)
1578
+ assert_equal(dtnat - tda, dtnat)
1579
+ assert_equal((dtb - tda).dtype, np.dtype('M8[D]'))
1580
+
1581
+ # In M8 - m8, the result goes to higher precision
1582
+ assert_equal(np.subtract(dtc, tdb, casting='unsafe'), dte)
1583
+ assert_equal(np.subtract(dtc, tdb, casting='unsafe').dtype,
1584
+ np.dtype('M8[h]'))
1585
+
1586
+ # M8 - M8 with different goes to higher precision
1587
+ assert_equal(np.subtract(dtc, dtd, casting='unsafe'),
1588
+ np.timedelta64(0, 'h'))
1589
+ assert_equal(np.subtract(dtc, dtd, casting='unsafe').dtype,
1590
+ np.dtype('m8[h]'))
1591
+ assert_equal(np.subtract(dtd, dtc, casting='unsafe'),
1592
+ np.timedelta64(0, 'h'))
1593
+ assert_equal(np.subtract(dtd, dtc, casting='unsafe').dtype,
1594
+ np.dtype('m8[h]'))
1595
+
1596
+ # m8 - M8
1597
+ assert_raises(TypeError, np.subtract, tda, dta)
1598
+ # bool - M8
1599
+ assert_raises(TypeError, np.subtract, False, dta)
1600
+ # int - M8
1601
+ assert_raises(TypeError, np.subtract, 3, dta)
1602
+
1603
+ def test_datetime_multiply(self):
1604
+ for dta, tda, tdb, tdc in \
1605
+ [
1606
+ # One-dimensional arrays
1607
+ (np.array(['2012-12-21'], dtype='M8[D]'),
1608
+ np.array([6], dtype='m8[h]'),
1609
+ np.array([9], dtype='m8[h]'),
1610
+ np.array([12], dtype='m8[h]')),
1611
+ # NumPy scalars
1612
+ (np.datetime64('2012-12-21', '[D]'),
1613
+ np.timedelta64(6, '[h]'),
1614
+ np.timedelta64(9, '[h]'),
1615
+ np.timedelta64(12, '[h]'))]:
1616
+ # m8 * int
1617
+ assert_equal(tda * 2, tdc)
1618
+ assert_equal((tda * 2).dtype, np.dtype('m8[h]'))
1619
+ # int * m8
1620
+ assert_equal(2 * tda, tdc)
1621
+ assert_equal((2 * tda).dtype, np.dtype('m8[h]'))
1622
+ # m8 * float
1623
+ assert_equal(tda * 1.5, tdb)
1624
+ assert_equal((tda * 1.5).dtype, np.dtype('m8[h]'))
1625
+ # float * m8
1626
+ assert_equal(1.5 * tda, tdb)
1627
+ assert_equal((1.5 * tda).dtype, np.dtype('m8[h]'))
1628
+
1629
+ # m8 * m8
1630
+ assert_raises(TypeError, np.multiply, tda, tdb)
1631
+ # m8 * M8
1632
+ assert_raises(TypeError, np.multiply, dta, tda)
1633
+ # M8 * m8
1634
+ assert_raises(TypeError, np.multiply, tda, dta)
1635
+ # M8 * int
1636
+ assert_raises(TypeError, np.multiply, dta, 2)
1637
+ # int * M8
1638
+ assert_raises(TypeError, np.multiply, 2, dta)
1639
+ # M8 * float
1640
+ assert_raises(TypeError, np.multiply, dta, 1.5)
1641
+ # float * M8
1642
+ assert_raises(TypeError, np.multiply, 1.5, dta)
1643
+
1644
+ # NaTs
1645
+ with warnings.catch_warnings():
1646
+ warnings.filterwarnings(
1647
+ 'ignore', "invalid value encountered in multiply", RuntimeWarning)
1648
+ nat = np.timedelta64('NaT', 's')
1649
+
1650
+ def check(a, b, res):
1651
+ assert_equal(a * b, res)
1652
+ assert_equal(b * a, res)
1653
+ for tp in (int, float):
1654
+ check(nat, tp(2), nat)
1655
+ check(nat, tp(0), nat)
1656
+ for f in (float('inf'), float('nan')):
1657
+ check(np.timedelta64(1, "s"), f, nat)
1658
+ check(np.timedelta64(0, "s"), f, nat)
1659
+ check(nat, f, nat)
1660
+
1661
+ @pytest.mark.parametrize("op1, op2, exp", [
1662
+ # m8 same units round down
1663
+ (np.timedelta64(7, 's'),
1664
+ np.timedelta64(4, 's'),
1665
+ 1),
1666
+ # m8 same units round down with negative
1667
+ (np.timedelta64(7, 's'),
1668
+ np.timedelta64(-4, 's'),
1669
+ -2),
1670
+ # m8 same units negative no round down
1671
+ (np.timedelta64(8, 's'),
1672
+ np.timedelta64(-4, 's'),
1673
+ -2),
1674
+ # m8 different units
1675
+ (np.timedelta64(1, 'm'),
1676
+ np.timedelta64(31, 's'),
1677
+ 1),
1678
+ # Y // M works
1679
+ (np.timedelta64(2, 'Y'),
1680
+ np.timedelta64('13', 'M'),
1681
+ 1),
1682
+ # handle 1D arrays
1683
+ (np.array([1, 2, 3], dtype='m8[s]'),
1684
+ np.array([2], dtype='m8[s]'),
1685
+ np.array([0, 1, 1], dtype=np.int64)),
1686
+ ])
1687
+ def test_timedelta_floor_divide(self, op1, op2, exp):
1688
+ assert_equal(op1 // op2, exp)
1689
+
1690
+ def test_generic_timedelta_floor_divide(self):
1691
+ with pytest.warns(
1692
+ DeprecationWarning,
1693
+ match=self.generic_unit_deprecation_message,
1694
+ ):
1695
+ assert_equal(np.timedelta64(1890) // np.timedelta64(31), 60)
1696
+
1697
+ @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
1698
+ @pytest.mark.parametrize("op1, op2", [
1699
+ # div by 0
1700
+ (np.timedelta64(10, 'us'),
1701
+ np.timedelta64(0, 'us')),
1702
+ # div with NaT
1703
+ (np.timedelta64('NaT', 'us'),
1704
+ np.timedelta64(50, 'us')),
1705
+ # special case for int64 min
1706
+ # in integer floor division
1707
+ (np.timedelta64(np.iinfo(np.int64).min, "s"),
1708
+ np.timedelta64(-1, "s")),
1709
+ ])
1710
+ def test_timedelta_floor_div_warnings(self, op1, op2):
1711
+ with pytest.warns(RuntimeWarning):
1712
+ actual = op1 // op2
1713
+ assert_equal(actual, 0)
1714
+ assert_equal(actual.dtype, np.int64)
1715
+
1716
+ @pytest.mark.parametrize("val1, val2", [
1717
+ # the smallest integer that can't be represented
1718
+ # exactly in a double should be preserved if we avoid
1719
+ # casting to double in floordiv operation
1720
+ (9007199254740993, 1),
1721
+ # stress the alternate floordiv code path where
1722
+ # operand signs don't match and remainder isn't 0
1723
+ (9007199254740999, -2),
1724
+ ])
1725
+ def test_timedelta_floor_div_precision(self, val1, val2):
1726
+ with pytest.warns(
1727
+ DeprecationWarning,
1728
+ match=self.generic_unit_deprecation_message,
1729
+ ):
1730
+ op1 = np.timedelta64(val1)
1731
+ op2 = np.timedelta64(val2)
1732
+ actual = op1 // op2
1733
+ # Python reference integer floor
1734
+ expected = val1 // val2
1735
+ assert_equal(actual, expected)
1736
+
1737
+ @pytest.mark.parametrize("val1, val2", [
1738
+ # years and months sometimes can't be unambiguously
1739
+ # divided for floor division operation
1740
+ (np.timedelta64(7, 'Y'),
1741
+ np.timedelta64(3, 's')),
1742
+ (np.timedelta64(7, 'M'),
1743
+ np.timedelta64(1, 'D')),
1744
+ ])
1745
+ def test_timedelta_floor_div_error(self, val1, val2):
1746
+ with assert_raises_regex(TypeError, "common metadata divisor"):
1747
+ val1 // val2
1748
+
1749
+ @pytest.mark.parametrize("op1, op2", [
1750
+ # reuse the test cases from floordiv
1751
+ (np.timedelta64(7, 's'),
1752
+ np.timedelta64(4, 's')),
1753
+ # m8 same units round down with negative
1754
+ (np.timedelta64(7, 's'),
1755
+ np.timedelta64(-4, 's')),
1756
+ # m8 same units negative no round down
1757
+ (np.timedelta64(8, 's'),
1758
+ np.timedelta64(-4, 's')),
1759
+ # m8 different units
1760
+ (np.timedelta64(1, 'm'),
1761
+ np.timedelta64(31, 's')),
1762
+ # Y // M works
1763
+ (np.timedelta64(2, 'Y'),
1764
+ np.timedelta64('13', 'M')),
1765
+ # handle 1D arrays
1766
+ (np.array([1, 2, 3], dtype='m8[ns]'),
1767
+ np.array([2], dtype='m8[ns]')),
1768
+ ])
1769
+ def test_timedelta_divmod(self, op1, op2):
1770
+ expected = (op1 // op2, op1 % op2)
1771
+ assert_equal(divmod(op1, op2), expected)
1772
+
1773
+ @pytest.mark.parametrize("op1, op2", [
1774
+ # m8 generic units
1775
+ (1890, 31),
1776
+ ])
1777
+ def test_generic_timedelta_divmod(self, op1, op2):
1778
+ with pytest.warns(
1779
+ DeprecationWarning,
1780
+ match=self.generic_unit_deprecation_message,
1781
+ ):
1782
+ op1 = np.timedelta64(op1)
1783
+ op2 = np.timedelta64(op2)
1784
+ expected = (op1 // op2, op1 % op2)
1785
+ assert_equal(divmod(op1, op2), expected)
1786
+
1787
+ @pytest.mark.parametrize("op1, op2", [
1788
+ # Y and M are incompatible with all units except Y and M
1789
+ (np.timedelta64(1, 'Y'), np.timedelta64(1, 's')),
1790
+ (np.timedelta64(1, 'D'), np.timedelta64(1, 'M')),
1791
+ ])
1792
+ def test_timedelta_divmod_typeerror(self, op1, op2):
1793
+ assert_raises(TypeError, np.divmod, op1, op2)
1794
+
1795
+ @pytest.mark.skipif(IS_WASM, reason="does not work in wasm")
1796
+ @pytest.mark.parametrize("op1, op2", [
1797
+ # reuse cases from floordiv
1798
+ # div by 0
1799
+ (np.timedelta64(10, 'us'),
1800
+ np.timedelta64(0, 'us')),
1801
+ # div with NaT
1802
+ (np.timedelta64('NaT', 'us'),
1803
+ np.timedelta64(50, 'us')),
1804
+ # special case for int64 min
1805
+ # in integer floor division
1806
+ (np.timedelta64(np.iinfo(np.int64).min, 'ns'),
1807
+ np.timedelta64(-1, 'ns')),
1808
+ ])
1809
+ def test_timedelta_divmod_warnings(self, op1, op2):
1810
+ with pytest.warns(RuntimeWarning):
1811
+ expected = (op1 // op2, op1 % op2)
1812
+ with pytest.warns(RuntimeWarning):
1813
+ actual = divmod(op1, op2)
1814
+ assert_equal(actual, expected)
1815
+
1816
+ def test_datetime_divide(self):
1817
+ for dta, tda, tdb, tdc, tdd in \
1818
+ [
1819
+ # One-dimensional arrays
1820
+ (np.array(['2012-12-21'], dtype='M8[D]'),
1821
+ np.array([6], dtype='m8[h]'),
1822
+ np.array([9], dtype='m8[h]'),
1823
+ np.array([12], dtype='m8[h]'),
1824
+ np.array([6], dtype='m8[m]')),
1825
+ # NumPy scalars
1826
+ (np.datetime64('2012-12-21', '[D]'),
1827
+ np.timedelta64(6, '[h]'),
1828
+ np.timedelta64(9, '[h]'),
1829
+ np.timedelta64(12, '[h]'),
1830
+ np.timedelta64(6, '[m]'))]:
1831
+ # m8 / int
1832
+ assert_equal(tdc / 2, tda)
1833
+ assert_equal((tdc / 2).dtype, np.dtype('m8[h]'))
1834
+ # m8 / float
1835
+ assert_equal(tda / 0.5, tdc)
1836
+ assert_equal((tda / 0.5).dtype, np.dtype('m8[h]'))
1837
+ # m8 / m8
1838
+ assert_equal(tda / tdb, 6 / 9)
1839
+ assert_equal(np.divide(tda, tdb), 6 / 9)
1840
+ assert_equal(np.true_divide(tda, tdb), 6 / 9)
1841
+ assert_equal(tdb / tda, 9 / 6)
1842
+ assert_equal((tda / tdb).dtype, np.dtype('f8'))
1843
+ assert_equal(tda / tdd, 60)
1844
+ assert_equal(tdd / tda, 1 / 60)
1845
+
1846
+ # int / m8
1847
+ assert_raises(TypeError, np.divide, 2, tdb)
1848
+ # float / m8
1849
+ assert_raises(TypeError, np.divide, 0.5, tdb)
1850
+ # m8 / M8
1851
+ assert_raises(TypeError, np.divide, dta, tda)
1852
+ # M8 / m8
1853
+ assert_raises(TypeError, np.divide, tda, dta)
1854
+ # M8 / int
1855
+ assert_raises(TypeError, np.divide, dta, 2)
1856
+ # int / M8
1857
+ assert_raises(TypeError, np.divide, 2, dta)
1858
+ # M8 / float
1859
+ assert_raises(TypeError, np.divide, dta, 1.5)
1860
+ # float / M8
1861
+ assert_raises(TypeError, np.divide, 1.5, dta)
1862
+
1863
+ # NaTs
1864
+ with warnings.catch_warnings():
1865
+ warnings.filterwarnings(
1866
+ 'ignore', r".*encountered in divide", RuntimeWarning)
1867
+ warnings.filterwarnings(
1868
+ "ignore",
1869
+ self.generic_unit_deprecation_message,
1870
+ DeprecationWarning,
1871
+ )
1872
+ nat = np.timedelta64('NaT', 's')
1873
+ for tp in (int, float):
1874
+ assert_equal(np.timedelta64(1) / tp(0), nat)
1875
+ assert_equal(np.timedelta64(0) / tp(0), nat)
1876
+ assert_equal(nat / tp(0), nat)
1877
+ assert_equal(nat / tp(2), nat)
1878
+ # Division by inf
1879
+ assert_equal(np.timedelta64(1) / float('inf'), np.timedelta64(0))
1880
+ assert_equal(np.timedelta64(0) / float('inf'), np.timedelta64(0))
1881
+ assert_equal(nat / float('inf'), nat)
1882
+ # Division by nan
1883
+ assert_equal(np.timedelta64(1) / float('nan'), nat)
1884
+ assert_equal(np.timedelta64(0) / float('nan'), nat)
1885
+ assert_equal(nat / float('nan'), nat)
1886
+
1887
+ def test_datetime_compare(self):
1888
+ # Test all the comparison operators
1889
+ a = np.datetime64('2000-03-12T18:00:00.000000')
1890
+ b = np.array(['2000-03-12T18:00:00.000000',
1891
+ '2000-03-12T17:59:59.999999',
1892
+ '2000-03-12T18:00:00.000001',
1893
+ '1970-01-11T12:00:00.909090',
1894
+ '2016-01-11T12:00:00.909090'],
1895
+ dtype='datetime64[us]')
1896
+ assert_equal(np.equal(a, b), [1, 0, 0, 0, 0])
1897
+ assert_equal(np.not_equal(a, b), [0, 1, 1, 1, 1])
1898
+ assert_equal(np.less(a, b), [0, 0, 1, 0, 1])
1899
+ assert_equal(np.less_equal(a, b), [1, 0, 1, 0, 1])
1900
+ assert_equal(np.greater(a, b), [0, 1, 0, 1, 0])
1901
+ assert_equal(np.greater_equal(a, b), [1, 1, 0, 1, 0])
1902
+
1903
+ def test_datetime_compare_nat(self):
1904
+ dt_nat = np.datetime64('NaT', 'D')
1905
+ dt_other = np.datetime64('2000-01-01')
1906
+ td_nat = np.timedelta64('NaT', 'h')
1907
+ td_other = np.timedelta64(1, 'h')
1908
+
1909
+ for op in [np.equal, np.less, np.less_equal,
1910
+ np.greater, np.greater_equal]:
1911
+ assert_(not op(dt_nat, dt_nat))
1912
+ assert_(not op(dt_nat, dt_other))
1913
+ assert_(not op(dt_other, dt_nat))
1914
+
1915
+ assert_(not op(td_nat, td_nat))
1916
+ assert_(not op(td_nat, td_other))
1917
+ assert_(not op(td_other, td_nat))
1918
+
1919
+ assert_(np.not_equal(dt_nat, dt_nat))
1920
+ assert_(np.not_equal(dt_nat, dt_other))
1921
+ assert_(np.not_equal(dt_other, dt_nat))
1922
+
1923
+ assert_(np.not_equal(td_nat, td_nat))
1924
+ assert_(np.not_equal(td_nat, td_other))
1925
+ assert_(np.not_equal(td_other, td_nat))
1926
+
1927
+ def test_datetime_minmax(self):
1928
+ # The metadata of the result should become the GCD
1929
+ # of the operand metadata
1930
+ a = np.array('1999-03-12T13', dtype='M8[2m]')
1931
+ b = np.array('1999-03-12T12', dtype='M8[s]')
1932
+ assert_equal(np.minimum(a, b), b)
1933
+ assert_equal(np.minimum(a, b).dtype, np.dtype('M8[s]'))
1934
+ assert_equal(np.fmin(a, b), b)
1935
+ assert_equal(np.fmin(a, b).dtype, np.dtype('M8[s]'))
1936
+ assert_equal(np.maximum(a, b), a)
1937
+ assert_equal(np.maximum(a, b).dtype, np.dtype('M8[s]'))
1938
+ assert_equal(np.fmax(a, b), a)
1939
+ assert_equal(np.fmax(a, b).dtype, np.dtype('M8[s]'))
1940
+ # Viewed as integers, the comparison is opposite because
1941
+ # of the units chosen
1942
+ assert_equal(np.minimum(a.view('i8'), b.view('i8')), a.view('i8'))
1943
+
1944
+ # Interaction with NaT
1945
+ a = np.array('1999-03-12T13', dtype='M8[2m]')
1946
+ dtnat = np.array('NaT', dtype='M8[h]')
1947
+ assert_equal(np.minimum(a, dtnat), dtnat)
1948
+ assert_equal(np.minimum(dtnat, a), dtnat)
1949
+ assert_equal(np.maximum(a, dtnat), dtnat)
1950
+ assert_equal(np.maximum(dtnat, a), dtnat)
1951
+ assert_equal(np.fmin(dtnat, a), a)
1952
+ assert_equal(np.fmin(a, dtnat), a)
1953
+ assert_equal(np.fmax(dtnat, a), a)
1954
+ assert_equal(np.fmax(a, dtnat), a)
1955
+
1956
+ # Also do timedelta
1957
+ a = np.array(3, dtype='m8[h]')
1958
+ b = np.array(3 * 3600 - 3, dtype='m8[s]')
1959
+ assert_equal(np.minimum(a, b), b)
1960
+ assert_equal(np.minimum(a, b).dtype, np.dtype('m8[s]'))
1961
+ assert_equal(np.fmin(a, b), b)
1962
+ assert_equal(np.fmin(a, b).dtype, np.dtype('m8[s]'))
1963
+ assert_equal(np.maximum(a, b), a)
1964
+ assert_equal(np.maximum(a, b).dtype, np.dtype('m8[s]'))
1965
+ assert_equal(np.fmax(a, b), a)
1966
+ assert_equal(np.fmax(a, b).dtype, np.dtype('m8[s]'))
1967
+ # Viewed as integers, the comparison is opposite because
1968
+ # of the units chosen
1969
+ assert_equal(np.minimum(a.view('i8'), b.view('i8')), a.view('i8'))
1970
+
1971
+ # should raise between datetime and timedelta
1972
+ #
1973
+ # TODO: Allowing unsafe casting by
1974
+ # default in ufuncs strikes again... :(
1975
+ a = np.array(3, dtype='m8[h]')
1976
+ b = np.array('1999-03-12T12', dtype='M8[s]')
1977
+ #assert_raises(TypeError, np.minimum, a, b)
1978
+ #assert_raises(TypeError, np.maximum, a, b)
1979
+ #assert_raises(TypeError, np.fmin, a, b)
1980
+ #assert_raises(TypeError, np.fmax, a, b)
1981
+ assert_raises(TypeError, np.minimum, a, b, casting='same_kind')
1982
+ assert_raises(TypeError, np.maximum, a, b, casting='same_kind')
1983
+ assert_raises(TypeError, np.fmin, a, b, casting='same_kind')
1984
+ assert_raises(TypeError, np.fmax, a, b, casting='same_kind')
1985
+
1986
+ def test_hours(self):
1987
+ t = np.ones(3, dtype='M8[s]')
1988
+ t[0] = 60 * 60 * 24 + 60 * 60 * 10
1989
+ assert_(t[0].item().hour == 10)
1990
+
1991
+ def test_divisor_conversion_year(self):
1992
+ assert_(np.dtype('M8[Y/4]') == np.dtype('M8[3M]'))
1993
+ assert_(np.dtype('M8[Y/13]') == np.dtype('M8[4W]'))
1994
+ assert_(np.dtype('M8[3Y/73]') == np.dtype('M8[15D]'))
1995
+
1996
+ def test_divisor_conversion_month(self):
1997
+ assert_(np.dtype('M8[M/2]') == np.dtype('M8[2W]'))
1998
+ assert_(np.dtype('M8[M/15]') == np.dtype('M8[2D]'))
1999
+ assert_(np.dtype('M8[3M/40]') == np.dtype('M8[54h]'))
2000
+
2001
+ def test_divisor_conversion_week(self):
2002
+ assert_(np.dtype('m8[W/7]') == np.dtype('m8[D]'))
2003
+ assert_(np.dtype('m8[3W/14]') == np.dtype('m8[36h]'))
2004
+ assert_(np.dtype('m8[5W/140]') == np.dtype('m8[360m]'))
2005
+
2006
+ def test_divisor_conversion_day(self):
2007
+ assert_(np.dtype('M8[D/12]') == np.dtype('M8[2h]'))
2008
+ assert_(np.dtype('M8[D/120]') == np.dtype('M8[12m]'))
2009
+ assert_(np.dtype('M8[3D/960]') == np.dtype('M8[270s]'))
2010
+
2011
+ def test_divisor_conversion_hour(self):
2012
+ assert_(np.dtype('m8[h/30]') == np.dtype('m8[2m]'))
2013
+ assert_(np.dtype('m8[3h/300]') == np.dtype('m8[36s]'))
2014
+
2015
+ def test_divisor_conversion_minute(self):
2016
+ assert_(np.dtype('m8[m/30]') == np.dtype('m8[2s]'))
2017
+ assert_(np.dtype('m8[3m/300]') == np.dtype('m8[600ms]'))
2018
+
2019
+ def test_divisor_conversion_second(self):
2020
+ assert_(np.dtype('m8[s/100]') == np.dtype('m8[10ms]'))
2021
+ assert_(np.dtype('m8[3s/10000]') == np.dtype('m8[300us]'))
2022
+
2023
+ def test_divisor_conversion_fs(self):
2024
+ assert_(np.dtype('M8[fs/100]') == np.dtype('M8[10as]'))
2025
+ assert_raises(ValueError, lambda: np.dtype('M8[3fs/10000]'))
2026
+
2027
+ def test_divisor_conversion_as(self):
2028
+ assert_raises(ValueError, lambda: np.dtype('M8[as/10]'))
2029
+
2030
+ def test_string_parser_variants(self):
2031
+ msg = "no explicit representation of timezones available for " \
2032
+ "np.datetime64"
2033
+ # Allow space instead of 'T' between date and time
2034
+ assert_equal(np.array(['1980-02-29T01:02:03'], np.dtype('M8[s]')),
2035
+ np.array(['1980-02-29 01:02:03'], np.dtype('M8[s]')))
2036
+ # Allow positive years
2037
+ assert_equal(np.array(['+1980-02-29T01:02:03'], np.dtype('M8[s]')),
2038
+ np.array(['+1980-02-29 01:02:03'], np.dtype('M8[s]')))
2039
+ # Allow negative years
2040
+ assert_equal(np.array(['-1980-02-29T01:02:03'], np.dtype('M8[s]')),
2041
+ np.array(['-1980-02-29 01:02:03'], np.dtype('M8[s]')))
2042
+ # UTC specifier
2043
+ with pytest.warns(UserWarning, match=msg):
2044
+ assert_equal(
2045
+ np.array(['+1980-02-29T01:02:03'], np.dtype('M8[s]')),
2046
+ np.array(['+1980-02-29 01:02:03Z'], np.dtype('M8[s]')))
2047
+ with pytest.warns(UserWarning, match=msg):
2048
+ assert_equal(
2049
+ np.array(['-1980-02-29T01:02:03'], np.dtype('M8[s]')),
2050
+ np.array(['-1980-02-29 01:02:03Z'], np.dtype('M8[s]')))
2051
+ # Time zone offset
2052
+ with pytest.warns(UserWarning, match=msg):
2053
+ assert_equal(
2054
+ np.array(['1980-02-29T02:02:03'], np.dtype('M8[s]')),
2055
+ np.array(['1980-02-29 00:32:03-0130'], np.dtype('M8[s]')))
2056
+ with pytest.warns(UserWarning, match=msg):
2057
+ assert_equal(
2058
+ np.array(['1980-02-28T22:32:03'], np.dtype('M8[s]')),
2059
+ np.array(['1980-02-29 00:02:03+01:30'], np.dtype('M8[s]')))
2060
+ with pytest.warns(UserWarning, match=msg):
2061
+ assert_equal(
2062
+ np.array(['1980-02-29T02:32:03.506'], np.dtype('M8[s]')),
2063
+ np.array(['1980-02-29 00:32:03.506-02'], np.dtype('M8[s]')))
2064
+ with pytest.warns(UserWarning, match=msg):
2065
+ assert_equal(np.datetime64('1977-03-02T12:30-0230'),
2066
+ np.datetime64('1977-03-02T15:00'))
2067
+
2068
+ def test_string_parser_error_check(self):
2069
+ msg = "no explicit representation of timezones available for " \
2070
+ "np.datetime64"
2071
+ # Arbitrary bad string
2072
+ assert_raises(ValueError, np.array, ['badvalue'], np.dtype('M8[us]'))
2073
+ # Character after year must be '-'
2074
+ assert_raises(ValueError, np.array, ['1980X'], np.dtype('M8[us]'))
2075
+ # Cannot have trailing '-'
2076
+ assert_raises(ValueError, np.array, ['1980-'], np.dtype('M8[us]'))
2077
+ # Month must be in range [1,12]
2078
+ assert_raises(ValueError, np.array, ['1980-00'], np.dtype('M8[us]'))
2079
+ assert_raises(ValueError, np.array, ['1980-13'], np.dtype('M8[us]'))
2080
+ # Month must have two digits
2081
+ assert_raises(ValueError, np.array, ['1980-1'], np.dtype('M8[us]'))
2082
+ assert_raises(ValueError, np.array, ['1980-1-02'], np.dtype('M8[us]'))
2083
+ # 'Mor' is not a valid month
2084
+ assert_raises(ValueError, np.array, ['1980-Mor'], np.dtype('M8[us]'))
2085
+ # Cannot have trailing '-'
2086
+ assert_raises(ValueError, np.array, ['1980-01-'], np.dtype('M8[us]'))
2087
+ # Day must be in range [1,len(month)]
2088
+ assert_raises(ValueError, np.array, ['1980-01-0'], np.dtype('M8[us]'))
2089
+ assert_raises(ValueError, np.array, ['1980-01-00'], np.dtype('M8[us]'))
2090
+ assert_raises(ValueError, np.array, ['1980-01-32'], np.dtype('M8[us]'))
2091
+ assert_raises(ValueError, np.array, ['1979-02-29'], np.dtype('M8[us]'))
2092
+ assert_raises(ValueError, np.array, ['1980-02-30'], np.dtype('M8[us]'))
2093
+ assert_raises(ValueError, np.array, ['1980-03-32'], np.dtype('M8[us]'))
2094
+ assert_raises(ValueError, np.array, ['1980-04-31'], np.dtype('M8[us]'))
2095
+ assert_raises(ValueError, np.array, ['1980-05-32'], np.dtype('M8[us]'))
2096
+ assert_raises(ValueError, np.array, ['1980-06-31'], np.dtype('M8[us]'))
2097
+ assert_raises(ValueError, np.array, ['1980-07-32'], np.dtype('M8[us]'))
2098
+ assert_raises(ValueError, np.array, ['1980-08-32'], np.dtype('M8[us]'))
2099
+ assert_raises(ValueError, np.array, ['1980-09-31'], np.dtype('M8[us]'))
2100
+ assert_raises(ValueError, np.array, ['1980-10-32'], np.dtype('M8[us]'))
2101
+ assert_raises(ValueError, np.array, ['1980-11-31'], np.dtype('M8[us]'))
2102
+ assert_raises(ValueError, np.array, ['1980-12-32'], np.dtype('M8[us]'))
2103
+ # Cannot have trailing characters
2104
+ assert_raises(ValueError, np.array, ['1980-02-03%'],
2105
+ np.dtype('M8[us]'))
2106
+ assert_raises(ValueError, np.array, ['1980-02-03 q'],
2107
+ np.dtype('M8[us]'))
2108
+
2109
+ # Hours must be in range [0, 23]
2110
+ assert_raises(ValueError, np.array, ['1980-02-03 25'],
2111
+ np.dtype('M8[us]'))
2112
+ assert_raises(ValueError, np.array, ['1980-02-03T25'],
2113
+ np.dtype('M8[us]'))
2114
+ assert_raises(ValueError, np.array, ['1980-02-03 24:01'],
2115
+ np.dtype('M8[us]'))
2116
+ assert_raises(ValueError, np.array, ['1980-02-03T24:01'],
2117
+ np.dtype('M8[us]'))
2118
+ assert_raises(ValueError, np.array, ['1980-02-03 -1'],
2119
+ np.dtype('M8[us]'))
2120
+ # No trailing ':'
2121
+ assert_raises(ValueError, np.array, ['1980-02-03 01:'],
2122
+ np.dtype('M8[us]'))
2123
+ # Minutes must be in range [0, 59]
2124
+ assert_raises(ValueError, np.array, ['1980-02-03 01:-1'],
2125
+ np.dtype('M8[us]'))
2126
+ assert_raises(ValueError, np.array, ['1980-02-03 01:60'],
2127
+ np.dtype('M8[us]'))
2128
+ # No trailing ':'
2129
+ assert_raises(ValueError, np.array, ['1980-02-03 01:60:'],
2130
+ np.dtype('M8[us]'))
2131
+ # Seconds must be in range [0, 59]
2132
+ assert_raises(ValueError, np.array, ['1980-02-03 01:10:-1'],
2133
+ np.dtype('M8[us]'))
2134
+ assert_raises(ValueError, np.array, ['1980-02-03 01:01:60'],
2135
+ np.dtype('M8[us]'))
2136
+ # Timezone offset must within a reasonable range
2137
+ with pytest.warns(UserWarning, match=msg):
2138
+ assert_raises(ValueError, np.array, ['1980-02-03 01:01:00+0661'],
2139
+ np.dtype('M8[us]'))
2140
+ with pytest.warns(UserWarning, match=msg):
2141
+ assert_raises(ValueError, np.array, ['1980-02-03 01:01:00+2500'],
2142
+ np.dtype('M8[us]'))
2143
+ with pytest.warns(UserWarning, match=msg):
2144
+ assert_raises(ValueError, np.array, ['1980-02-03 01:01:00-0070'],
2145
+ np.dtype('M8[us]'))
2146
+ with pytest.warns(UserWarning, match=msg):
2147
+ assert_raises(ValueError, np.array, ['1980-02-03 01:01:00-3000'],
2148
+ np.dtype('M8[us]'))
2149
+ with pytest.warns(UserWarning, match=msg):
2150
+ assert_raises(ValueError, np.array, ['1980-02-03 01:01:00-25:00'],
2151
+ np.dtype('M8[us]'))
2152
+
2153
+ def test_creation_overflow(self):
2154
+ date = '1980-03-23 20:00:00'
2155
+ timesteps = np.array([date], dtype='datetime64[s]')[0].astype(np.int64)
2156
+ for unit in ['ms', 'us', 'ns']:
2157
+ timesteps *= 1000
2158
+ x = np.array([date], dtype=f'datetime64[{unit}]')
2159
+
2160
+ assert_equal(timesteps, x[0].astype(np.int64),
2161
+ err_msg=f'Datetime conversion error for unit {unit}')
2162
+
2163
+ assert_equal(x[0].astype(np.int64), 322689600000000000)
2164
+
2165
+ # gh-13062
2166
+ with pytest.raises(OverflowError):
2167
+ np.datetime64(2**64, 'D')
2168
+ with pytest.raises(OverflowError):
2169
+ np.timedelta64(2**64, 'D')
2170
+
2171
+ def test_datetime_as_string(self):
2172
+ # Check all the units with default string conversion
2173
+ date = '1959-10-13'
2174
+ datetime = '1959-10-13T12:34:56.789012345678901234'
2175
+
2176
+ assert_equal(np.datetime_as_string(np.datetime64(date, 'Y')),
2177
+ '1959')
2178
+ assert_equal(np.datetime_as_string(np.datetime64(date, 'M')),
2179
+ '1959-10')
2180
+ assert_equal(np.datetime_as_string(np.datetime64(date, 'D')),
2181
+ '1959-10-13')
2182
+ assert_equal(np.datetime_as_string(np.datetime64(datetime, 'h')),
2183
+ '1959-10-13T12')
2184
+ assert_equal(np.datetime_as_string(np.datetime64(datetime, 'm')),
2185
+ '1959-10-13T12:34')
2186
+ assert_equal(np.datetime_as_string(np.datetime64(datetime, 's')),
2187
+ '1959-10-13T12:34:56')
2188
+ assert_equal(np.datetime_as_string(np.datetime64(datetime, 'ms')),
2189
+ '1959-10-13T12:34:56.789')
2190
+ for us in ['us', 'μs', b'us']: # check non-ascii and bytes too
2191
+ assert_equal(np.datetime_as_string(np.datetime64(datetime, us)),
2192
+ '1959-10-13T12:34:56.789012')
2193
+
2194
+ datetime = '1969-12-31T23:34:56.789012345678901234'
2195
+
2196
+ assert_equal(np.datetime_as_string(np.datetime64(datetime, 'ns')),
2197
+ '1969-12-31T23:34:56.789012345')
2198
+ assert_equal(np.datetime_as_string(np.datetime64(datetime, 'ps')),
2199
+ '1969-12-31T23:34:56.789012345678')
2200
+ assert_equal(np.datetime_as_string(np.datetime64(datetime, 'fs')),
2201
+ '1969-12-31T23:34:56.789012345678901')
2202
+
2203
+ datetime = '1969-12-31T23:59:57.789012345678901234'
2204
+
2205
+ assert_equal(np.datetime_as_string(np.datetime64(datetime, 'as')),
2206
+ datetime)
2207
+ datetime = '1970-01-01T00:34:56.789012345678901234'
2208
+
2209
+ assert_equal(np.datetime_as_string(np.datetime64(datetime, 'ns')),
2210
+ '1970-01-01T00:34:56.789012345')
2211
+ assert_equal(np.datetime_as_string(np.datetime64(datetime, 'ps')),
2212
+ '1970-01-01T00:34:56.789012345678')
2213
+ assert_equal(np.datetime_as_string(np.datetime64(datetime, 'fs')),
2214
+ '1970-01-01T00:34:56.789012345678901')
2215
+
2216
+ datetime = '1970-01-01T00:00:05.789012345678901234'
2217
+
2218
+ assert_equal(np.datetime_as_string(np.datetime64(datetime, 'as')),
2219
+ datetime)
2220
+
2221
+ # String conversion with the unit= parameter
2222
+ a = np.datetime64('2032-07-18T12:23:34.123456', 'us')
2223
+ assert_equal(np.datetime_as_string(a, unit='Y', casting='unsafe'),
2224
+ '2032')
2225
+ assert_equal(np.datetime_as_string(a, unit='M', casting='unsafe'),
2226
+ '2032-07')
2227
+ assert_equal(np.datetime_as_string(a, unit='W', casting='unsafe'),
2228
+ '2032-07-18')
2229
+ assert_equal(np.datetime_as_string(a, unit='D', casting='unsafe'),
2230
+ '2032-07-18')
2231
+
2232
+ with pytest.raises(ValueError):
2233
+ np.datetime_as_string(a, unit='Y', casting='same_value')
2234
+
2235
+ assert_equal(np.datetime_as_string(a, unit='h'), '2032-07-18T12')
2236
+ assert_equal(np.datetime_as_string(a, unit='m'),
2237
+ '2032-07-18T12:23')
2238
+ assert_equal(np.datetime_as_string(a, unit='s'),
2239
+ '2032-07-18T12:23:34')
2240
+ assert_equal(np.datetime_as_string(a, unit='ms'),
2241
+ '2032-07-18T12:23:34.123')
2242
+ assert_equal(np.datetime_as_string(a, unit='us'),
2243
+ '2032-07-18T12:23:34.123456')
2244
+ assert_equal(np.datetime_as_string(a, unit='ns'),
2245
+ '2032-07-18T12:23:34.123456000')
2246
+ assert_equal(np.datetime_as_string(a, unit='ps'),
2247
+ '2032-07-18T12:23:34.123456000000')
2248
+ assert_equal(np.datetime_as_string(a, unit='fs'),
2249
+ '2032-07-18T12:23:34.123456000000000')
2250
+ assert_equal(np.datetime_as_string(a, unit='as'),
2251
+ '2032-07-18T12:23:34.123456000000000000')
2252
+
2253
+ # unit='auto' parameter
2254
+ assert_equal(np.datetime_as_string(
2255
+ np.datetime64('2032-07-18T12:23:34.123456', 'us'), unit='auto'),
2256
+ '2032-07-18T12:23:34.123456')
2257
+ assert_equal(np.datetime_as_string(
2258
+ np.datetime64('2032-07-18T12:23:34.12', 'us'), unit='auto'),
2259
+ '2032-07-18T12:23:34.120')
2260
+ assert_equal(np.datetime_as_string(
2261
+ np.datetime64('2032-07-18T12:23:34', 'us'), unit='auto'),
2262
+ '2032-07-18T12:23:34')
2263
+ assert_equal(np.datetime_as_string(
2264
+ np.datetime64('2032-07-18T12:23:00', 'us'), unit='auto'),
2265
+ '2032-07-18T12:23')
2266
+ # 'auto' doesn't split up hour and minute
2267
+ assert_equal(np.datetime_as_string(
2268
+ np.datetime64('2032-07-18T12:00:00', 'us'), unit='auto'),
2269
+ '2032-07-18T12:00')
2270
+ assert_equal(np.datetime_as_string(
2271
+ np.datetime64('2032-07-18T00:00:00', 'us'), unit='auto'),
2272
+ '2032-07-18')
2273
+ # 'auto' doesn't split up the date
2274
+ assert_equal(np.datetime_as_string(
2275
+ np.datetime64('2032-07-01T00:00:00', 'us'), unit='auto'),
2276
+ '2032-07-01')
2277
+ assert_equal(np.datetime_as_string(
2278
+ np.datetime64('2032-01-01T00:00:00', 'us'), unit='auto'),
2279
+ '2032-01-01')
2280
+
2281
+ @pytest.mark.skipif(not _has_tz, reason="The tzdata module is not available.")
2282
+ def test_datetime_as_string_timezone(self):
2283
+ # timezone='local' vs 'UTC'
2284
+ a = np.datetime64('2010-03-15T06:30', 'm')
2285
+ assert_equal(np.datetime_as_string(a),
2286
+ '2010-03-15T06:30')
2287
+ assert_equal(np.datetime_as_string(a, timezone='naive'),
2288
+ '2010-03-15T06:30')
2289
+ assert_equal(np.datetime_as_string(a, timezone='UTC'),
2290
+ '2010-03-15T06:30Z')
2291
+ assert_(np.datetime_as_string(a, timezone='local') !=
2292
+ '2010-03-15T06:30')
2293
+
2294
+ b = np.datetime64('2010-02-15T06:30', 'm')
2295
+
2296
+ assert_equal(np.datetime_as_string(a, timezone=ZoneInfo('US/Central')),
2297
+ '2010-03-15T01:30-0500')
2298
+ assert_equal(np.datetime_as_string(a, timezone=ZoneInfo('US/Eastern')),
2299
+ '2010-03-15T02:30-0400')
2300
+ assert_equal(np.datetime_as_string(a, timezone=ZoneInfo('US/Pacific')),
2301
+ '2010-03-14T23:30-0700')
2302
+
2303
+ assert_equal(np.datetime_as_string(b, timezone=ZoneInfo('US/Central')),
2304
+ '2010-02-15T00:30-0600')
2305
+ assert_equal(np.datetime_as_string(b, timezone=ZoneInfo('US/Eastern')),
2306
+ '2010-02-15T01:30-0500')
2307
+ assert_equal(np.datetime_as_string(b, timezone=ZoneInfo('US/Pacific')),
2308
+ '2010-02-14T22:30-0800')
2309
+
2310
+ # Dates to strings with a timezone attached is disabled by default
2311
+ assert_raises(TypeError, np.datetime_as_string, a, unit='D',
2312
+ timezone=ZoneInfo('US/Pacific'))
2313
+ # Check that we can print out the date in the specified time zone
2314
+ assert_equal(np.datetime_as_string(a, unit='D',
2315
+ timezone=ZoneInfo('US/Pacific'), casting='unsafe'),
2316
+ '2010-03-14')
2317
+ assert_equal(np.datetime_as_string(b, unit='D',
2318
+ timezone=ZoneInfo('US/Central'), casting='unsafe'),
2319
+ '2010-02-15')
2320
+
2321
+ def test_datetime_arange(self):
2322
+ # With two datetimes provided as strings
2323
+ a = np.arange('2010-01-05', '2010-01-10', dtype='M8[D]')
2324
+ assert_equal(a.dtype, np.dtype('M8[D]'))
2325
+ assert_equal(a,
2326
+ np.array(['2010-01-05', '2010-01-06', '2010-01-07',
2327
+ '2010-01-08', '2010-01-09'], dtype='M8[D]'))
2328
+
2329
+ a = np.arange('1950-02-10', '1950-02-06', -1, dtype='M8[D]')
2330
+ assert_equal(a.dtype, np.dtype('M8[D]'))
2331
+ assert_equal(a,
2332
+ np.array(['1950-02-10', '1950-02-09', '1950-02-08',
2333
+ '1950-02-07'], dtype='M8[D]'))
2334
+
2335
+ with pytest.warns(
2336
+ DeprecationWarning,
2337
+ match=self.generic_unit_deprecation_message,
2338
+ ):
2339
+ # Unit should be detected as months here
2340
+ a = np.arange("1969-05", "1970-05", 2, dtype="M8")
2341
+ assert_equal(a.dtype, np.dtype('M8[M]'))
2342
+ assert_equal(a,
2343
+ np.datetime64('1969-05') + np.arange(12, step=2))
2344
+
2345
+ # datetime, integer|timedelta works as well
2346
+ # produces arange (start, start + stop) in this case
2347
+ a = np.arange('1969', 18, 3, dtype='M8')
2348
+ assert_equal(a.dtype, np.dtype('M8[Y]'))
2349
+ assert_equal(a,
2350
+ np.datetime64('1969') + np.arange(18, step=3))
2351
+ a = np.arange('1969-12-19', 22, np.timedelta64(2), dtype='M8')
2352
+ assert_equal(a.dtype, np.dtype('M8[D]'))
2353
+ assert_equal(a,
2354
+ np.datetime64('1969-12-19') + np.arange(22, step=2))
2355
+
2356
+ # Step of 0 is disallowed
2357
+ assert_raises(
2358
+ ValueError,
2359
+ np.arange,
2360
+ np.datetime64("today"),
2361
+ np.datetime64("today") + np.timedelta64(3, "D"),
2362
+ np.timedelta64(0, "D"),
2363
+ )
2364
+ # Promotion across nonlinear unit boundaries is disallowed
2365
+ assert_raises(TypeError, np.arange, np.datetime64('2011-03-01', 'D'),
2366
+ np.timedelta64(5, 'M'))
2367
+ assert_raises(TypeError, np.arange,
2368
+ np.datetime64('2012-02-03T14', 's'),
2369
+ np.timedelta64(5, 'Y'))
2370
+
2371
+ def test_datetime_arange_no_dtype(self):
2372
+ d = np.array('2010-01-04', dtype="M8[D]")
2373
+ assert_equal(np.arange(d, d + np.timedelta64(1, "D")), d)
2374
+ assert_raises(ValueError, np.arange, d)
2375
+
2376
+ def test_timedelta_arange(self):
2377
+ a = np.arange(3, 10, dtype='m8[s]')
2378
+ assert_equal(a.dtype, np.dtype('m8[s]'))
2379
+ assert_equal(a, np.timedelta64(0, "s") + np.arange(3, 10, dtype="m8[s]"))
2380
+
2381
+ a = np.arange(
2382
+ np.timedelta64(3, "s"),
2383
+ np.timedelta64(10, "s"),
2384
+ np.timedelta64(2, "s"),
2385
+ dtype="m8",
2386
+ )
2387
+ assert_equal(a.dtype, np.dtype('m8[s]'))
2388
+ assert_equal(a, np.timedelta64(0, 's') + np.arange(3, 10, 2))
2389
+
2390
+ # Step of 0 is disallowed
2391
+ assert_raises(ValueError, np.arange, np.timedelta64(0, 's'),
2392
+ np.timedelta64(5, 's'), np.timedelta64(0, 's'))
2393
+ # Promotion across nonlinear unit boundaries is disallowed
2394
+ assert_raises(TypeError, np.arange, np.timedelta64(0, 'D'),
2395
+ np.timedelta64(5, 'M'))
2396
+ assert_raises(TypeError, np.arange, np.timedelta64(0, 'Y'),
2397
+ np.timedelta64(5, 'D'))
2398
+
2399
+ @pytest.mark.parametrize("val1, val2, expected", [
2400
+ # case from gh-12092
2401
+ (np.timedelta64(7, 's'),
2402
+ np.timedelta64(3, 's'),
2403
+ np.timedelta64(1, 's')),
2404
+ # negative value cases
2405
+ (np.timedelta64(3, 's'),
2406
+ np.timedelta64(-2, 's'),
2407
+ np.timedelta64(-1, 's')),
2408
+ (np.timedelta64(-3, 's'),
2409
+ np.timedelta64(2, 's'),
2410
+ np.timedelta64(1, 's')),
2411
+ # larger value cases
2412
+ (np.timedelta64(17, 's'),
2413
+ np.timedelta64(22, 's'),
2414
+ np.timedelta64(17, 's')),
2415
+ (np.timedelta64(22, 's'),
2416
+ np.timedelta64(17, 's'),
2417
+ np.timedelta64(5, 's')),
2418
+ # different units
2419
+ (np.timedelta64(1, 'm'),
2420
+ np.timedelta64(57, 's'),
2421
+ np.timedelta64(3, 's')),
2422
+ (np.timedelta64(1, 'us'),
2423
+ np.timedelta64(727, 'ns'),
2424
+ np.timedelta64(273, 'ns')),
2425
+ # NaT is propagated
2426
+ (np.timedelta64('NaT', 'ns'),
2427
+ np.timedelta64(50, 'ns'),
2428
+ np.timedelta64('NaT', 'ns')),
2429
+ # Y % M works
2430
+ (np.timedelta64(2, 'Y'),
2431
+ np.timedelta64(22, 'M'),
2432
+ np.timedelta64(2, 'M')),
2433
+ ])
2434
+ def test_timedelta_modulus(self, val1, val2, expected):
2435
+ assert_equal(val1 % val2, expected)
2436
+
2437
+ @pytest.mark.parametrize("val1, val2", [
2438
+ # years and months sometimes can't be unambiguously
2439
+ # divided for modulus operation
2440
+ (np.timedelta64(7, 'Y'),
2441
+ np.timedelta64(3, 's')),
2442
+ (np.timedelta64(7, 'M'),
2443
+ np.timedelta64(1, 'D')),
2444
+ ])
2445
+ def test_timedelta_modulus_error(self, val1, val2):
2446
+ with assert_raises_regex(TypeError, "common metadata divisor"):
2447
+ val1 % val2
2448
+
2449
+ @pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
2450
+ def test_timedelta_modulus_div_by_zero(self):
2451
+ with pytest.warns(RuntimeWarning):
2452
+ actual = np.timedelta64(10, 's') % np.timedelta64(0, 's')
2453
+ assert_equal(actual, np.timedelta64('NaT', 's'))
2454
+
2455
+ @pytest.mark.parametrize("val1, val2", [
2456
+ # cases where one operand is not
2457
+ # timedelta64
2458
+ (np.timedelta64(7, 'Y'),
2459
+ 15,),
2460
+ (7.5,
2461
+ np.timedelta64(1, 'D')),
2462
+ ])
2463
+ def test_timedelta_modulus_type_resolution(self, val1, val2):
2464
+ # NOTE: some of the operations may be supported
2465
+ # in the future
2466
+ with assert_raises_regex(TypeError,
2467
+ "'remainder' cannot use operands with types"):
2468
+ val1 % val2
2469
+
2470
+ def test_timedelta_arange_no_dtype(self):
2471
+ d = np.array(5, dtype="m8[D]")
2472
+ assert_equal(np.arange(d, d + np.timedelta64(1, "D")), d)
2473
+ assert_equal(np.arange(d), np.arange(np.timedelta64(0, "D"), d))
2474
+
2475
+ def test_datetime_maximum_reduce(self):
2476
+ a = np.array(['2010-01-02', '1999-03-14', '1833-03'], dtype='M8[D]')
2477
+ assert_equal(np.maximum.reduce(a).dtype, np.dtype('M8[D]'))
2478
+ assert_equal(np.maximum.reduce(a),
2479
+ np.datetime64('2010-01-02'))
2480
+
2481
+ a = np.array([1, 4, 0, 7, 2], dtype='m8[s]')
2482
+ assert_equal(np.maximum.reduce(a).dtype, np.dtype('m8[s]'))
2483
+ assert_equal(np.maximum.reduce(a),
2484
+ np.timedelta64(7, 's'))
2485
+
2486
+ def test_timedelta_correct_mean(self):
2487
+ # test mainly because it worked only via a bug in that allowed:
2488
+ # `timedelta.sum(dtype="f8")` to ignore the dtype request.
2489
+ a = np.arange(1000, dtype="m8[s]")
2490
+ assert_array_equal(a.mean(), a.sum() / len(a))
2491
+
2492
+ def test_datetime_no_subtract_reducelike(self):
2493
+ # subtracting two datetime64 works, but we cannot reduce it, since
2494
+ # the result of that subtraction will have a different dtype.
2495
+ arr = np.array(["2021-12-02", "2019-05-12"], dtype="M8[ms]")
2496
+ msg = r"the resolved dtypes are not compatible"
2497
+
2498
+ with pytest.raises(TypeError, match=msg):
2499
+ np.subtract.reduce(arr)
2500
+
2501
+ with pytest.raises(TypeError, match=msg):
2502
+ np.subtract.accumulate(arr)
2503
+
2504
+ with pytest.raises(TypeError, match=msg):
2505
+ np.subtract.reduceat(arr, [0])
2506
+
2507
+ def test_datetime_busday_offset(self):
2508
+ # First Monday in June
2509
+ assert_equal(
2510
+ np.busday_offset('2011-06', 0, roll='forward', weekmask='Mon'),
2511
+ np.datetime64('2011-06-06'))
2512
+ # Last Monday in June
2513
+ assert_equal(
2514
+ np.busday_offset('2011-07', -1, roll='forward', weekmask='Mon'),
2515
+ np.datetime64('2011-06-27'))
2516
+ assert_equal(
2517
+ np.busday_offset('2011-07', -1, roll='forward', weekmask='Mon'),
2518
+ np.datetime64('2011-06-27'))
2519
+
2520
+ # Default M-F business days, different roll modes
2521
+ assert_equal(np.busday_offset('2010-08', 0, roll='backward'),
2522
+ np.datetime64('2010-07-30'))
2523
+ assert_equal(np.busday_offset('2010-08', 0, roll='preceding'),
2524
+ np.datetime64('2010-07-30'))
2525
+ assert_equal(np.busday_offset('2010-08', 0, roll='modifiedpreceding'),
2526
+ np.datetime64('2010-08-02'))
2527
+ assert_equal(np.busday_offset('2010-08', 0, roll='modifiedfollowing'),
2528
+ np.datetime64('2010-08-02'))
2529
+ assert_equal(np.busday_offset('2010-08', 0, roll='forward'),
2530
+ np.datetime64('2010-08-02'))
2531
+ assert_equal(np.busday_offset('2010-08', 0, roll='following'),
2532
+ np.datetime64('2010-08-02'))
2533
+ assert_equal(np.busday_offset('2010-10-30', 0, roll='following'),
2534
+ np.datetime64('2010-11-01'))
2535
+ assert_equal(
2536
+ np.busday_offset('2010-10-30', 0, roll='modifiedfollowing'),
2537
+ np.datetime64('2010-10-29'))
2538
+ assert_equal(
2539
+ np.busday_offset('2010-10-30', 0, roll='modifiedpreceding'),
2540
+ np.datetime64('2010-10-29'))
2541
+ assert_equal(
2542
+ np.busday_offset('2010-10-16', 0, roll='modifiedfollowing'),
2543
+ np.datetime64('2010-10-18'))
2544
+ assert_equal(
2545
+ np.busday_offset('2010-10-16', 0, roll='modifiedpreceding'),
2546
+ np.datetime64('2010-10-15'))
2547
+ # roll='raise' by default
2548
+ assert_raises(ValueError, np.busday_offset, '2011-06-04', 0)
2549
+
2550
+ # Bigger offset values
2551
+ assert_equal(np.busday_offset('2006-02-01', 25),
2552
+ np.datetime64('2006-03-08'))
2553
+ assert_equal(np.busday_offset('2006-03-08', -25),
2554
+ np.datetime64('2006-02-01'))
2555
+ assert_equal(np.busday_offset('2007-02-25', 11, weekmask='SatSun'),
2556
+ np.datetime64('2007-04-07'))
2557
+ assert_equal(np.busday_offset('2007-04-07', -11, weekmask='SatSun'),
2558
+ np.datetime64('2007-02-25'))
2559
+
2560
+ # NaT values when roll is not raise
2561
+ assert_equal(np.busday_offset(np.datetime64('NaT', 'D'), 1, roll='nat'),
2562
+ np.datetime64('NaT', 'D'))
2563
+ assert_equal(np.busday_offset(np.datetime64('NaT', 'D'), 1, roll='following'),
2564
+ np.datetime64('NaT', 'D'))
2565
+ assert_equal(np.busday_offset(np.datetime64('NaT', 'D'), 1, roll='preceding'),
2566
+ np.datetime64('NaT', 'D'))
2567
+
2568
+ def test_datetime_busdaycalendar(self):
2569
+ # Check that it removes NaT, duplicates, and weekends
2570
+ # and sorts the result.
2571
+ bdd = np.busdaycalendar(
2572
+ holidays=['NaT', '2011-01-17', '2011-03-06', 'NaT',
2573
+ '2011-12-26', '2011-05-30', '2011-01-17'])
2574
+ assert_equal(bdd.holidays,
2575
+ np.array(['2011-01-17', '2011-05-30', '2011-12-26'], dtype='M8'))
2576
+ # Default M-F weekmask
2577
+ assert_equal(bdd.weekmask, np.array([1, 1, 1, 1, 1, 0, 0], dtype='?'))
2578
+
2579
+ # Check string weekmask with varying whitespace.
2580
+ bdd = np.busdaycalendar(weekmask="Sun TueWed Thu\tFri")
2581
+ assert_equal(bdd.weekmask, np.array([0, 1, 1, 1, 1, 0, 1], dtype='?'))
2582
+
2583
+ # Check length 7 0/1 string
2584
+ bdd = np.busdaycalendar(weekmask="0011001")
2585
+ assert_equal(bdd.weekmask, np.array([0, 0, 1, 1, 0, 0, 1], dtype='?'))
2586
+
2587
+ # Check length 7 bool array.
2588
+ mask = np.array([False, True, True, True, True, False, False])
2589
+ bdd = np.busdaycalendar(weekmask=mask)
2590
+ assert_equal(bdd.weekmask, mask, strict=True)
2591
+
2592
+ # Check length 7 string weekmask.
2593
+ bdd = np.busdaycalendar(weekmask="Mon Tue")
2594
+ assert_equal(bdd.weekmask, np.array([1, 1, 0, 0, 0, 0, 0], dtype='?'))
2595
+
2596
+ # All-zeros weekmask should raise
2597
+ assert_raises(ValueError, np.busdaycalendar, weekmask=[0, 0, 0, 0, 0, 0, 0])
2598
+ # weekday names must be correct case
2599
+ assert_raises(ValueError, np.busdaycalendar, weekmask="satsun")
2600
+ # All-zeros weekmask should raise
2601
+ assert_raises(ValueError, np.busdaycalendar, weekmask="")
2602
+ # Invalid weekday name codes should raise
2603
+ assert_raises(ValueError, np.busdaycalendar, weekmask="Mon Tue We")
2604
+ assert_raises(ValueError, np.busdaycalendar, weekmask="Max")
2605
+ assert_raises(ValueError, np.busdaycalendar, weekmask="Monday Tue")
2606
+
2607
+ def test_datetime_busday_holidays_offset(self):
2608
+ # With exactly one holiday
2609
+ assert_equal(
2610
+ np.busday_offset('2011-11-10', 1, holidays=['2011-11-11']),
2611
+ np.datetime64('2011-11-14'))
2612
+ assert_equal(
2613
+ np.busday_offset('2011-11-04', 5, holidays=['2011-11-11']),
2614
+ np.datetime64('2011-11-14'))
2615
+ assert_equal(
2616
+ np.busday_offset('2011-11-10', 5, holidays=['2011-11-11']),
2617
+ np.datetime64('2011-11-18'))
2618
+ assert_equal(
2619
+ np.busday_offset('2011-11-14', -1, holidays=['2011-11-11']),
2620
+ np.datetime64('2011-11-10'))
2621
+ assert_equal(
2622
+ np.busday_offset('2011-11-18', -5, holidays=['2011-11-11']),
2623
+ np.datetime64('2011-11-10'))
2624
+ assert_equal(
2625
+ np.busday_offset('2011-11-14', -5, holidays=['2011-11-11']),
2626
+ np.datetime64('2011-11-04'))
2627
+ # With the holiday appearing twice
2628
+ assert_equal(
2629
+ np.busday_offset('2011-11-10', 1,
2630
+ holidays=['2011-11-11', '2011-11-11']),
2631
+ np.datetime64('2011-11-14'))
2632
+ assert_equal(
2633
+ np.busday_offset('2011-11-14', -1,
2634
+ holidays=['2011-11-11', '2011-11-11']),
2635
+ np.datetime64('2011-11-10'))
2636
+ # With a NaT holiday
2637
+ assert_equal(
2638
+ np.busday_offset('2011-11-10', 1,
2639
+ holidays=['2011-11-11', 'NaT']),
2640
+ np.datetime64('2011-11-14'))
2641
+ assert_equal(
2642
+ np.busday_offset('2011-11-14', -1,
2643
+ holidays=['NaT', '2011-11-11']),
2644
+ np.datetime64('2011-11-10'))
2645
+ # With another holiday after
2646
+ assert_equal(
2647
+ np.busday_offset('2011-11-10', 1,
2648
+ holidays=['2011-11-11', '2011-11-24']),
2649
+ np.datetime64('2011-11-14'))
2650
+ assert_equal(
2651
+ np.busday_offset('2011-11-14', -1,
2652
+ holidays=['2011-11-11', '2011-11-24']),
2653
+ np.datetime64('2011-11-10'))
2654
+ # With another holiday before
2655
+ assert_equal(
2656
+ np.busday_offset('2011-11-10', 1,
2657
+ holidays=['2011-10-10', '2011-11-11']),
2658
+ np.datetime64('2011-11-14'))
2659
+ assert_equal(
2660
+ np.busday_offset('2011-11-14', -1,
2661
+ holidays=['2011-10-10', '2011-11-11']),
2662
+ np.datetime64('2011-11-10'))
2663
+ # With another holiday before and after
2664
+ assert_equal(
2665
+ np.busday_offset('2011-11-10', 1,
2666
+ holidays=['2011-10-10', '2011-11-11', '2011-11-24']),
2667
+ np.datetime64('2011-11-14'))
2668
+ assert_equal(
2669
+ np.busday_offset('2011-11-14', -1,
2670
+ holidays=['2011-10-10', '2011-11-11', '2011-11-24']),
2671
+ np.datetime64('2011-11-10'))
2672
+
2673
+ # A bigger forward jump across more than one week/holiday
2674
+ holidays = ['2011-10-10', '2011-11-11', '2011-11-24',
2675
+ '2011-12-25', '2011-05-30', '2011-02-21',
2676
+ '2011-12-26', '2012-01-02']
2677
+ bdd = np.busdaycalendar(weekmask='1111100', holidays=holidays)
2678
+ assert_equal(
2679
+ np.busday_offset('2011-10-03', 4, holidays=holidays),
2680
+ np.busday_offset('2011-10-03', 4))
2681
+ assert_equal(
2682
+ np.busday_offset('2011-10-03', 5, holidays=holidays),
2683
+ np.busday_offset('2011-10-03', 5 + 1))
2684
+ assert_equal(
2685
+ np.busday_offset('2011-10-03', 27, holidays=holidays),
2686
+ np.busday_offset('2011-10-03', 27 + 1))
2687
+ assert_equal(
2688
+ np.busday_offset('2011-10-03', 28, holidays=holidays),
2689
+ np.busday_offset('2011-10-03', 28 + 2))
2690
+ assert_equal(
2691
+ np.busday_offset('2011-10-03', 35, holidays=holidays),
2692
+ np.busday_offset('2011-10-03', 35 + 2))
2693
+ assert_equal(
2694
+ np.busday_offset('2011-10-03', 36, holidays=holidays),
2695
+ np.busday_offset('2011-10-03', 36 + 3))
2696
+ assert_equal(
2697
+ np.busday_offset('2011-10-03', 56, holidays=holidays),
2698
+ np.busday_offset('2011-10-03', 56 + 3))
2699
+ assert_equal(
2700
+ np.busday_offset('2011-10-03', 57, holidays=holidays),
2701
+ np.busday_offset('2011-10-03', 57 + 4))
2702
+ assert_equal(
2703
+ np.busday_offset('2011-10-03', 60, holidays=holidays),
2704
+ np.busday_offset('2011-10-03', 60 + 4))
2705
+ assert_equal(
2706
+ np.busday_offset('2011-10-03', 61, holidays=holidays),
2707
+ np.busday_offset('2011-10-03', 61 + 5))
2708
+ assert_equal(
2709
+ np.busday_offset('2011-10-03', 61, busdaycal=bdd),
2710
+ np.busday_offset('2011-10-03', 61 + 5))
2711
+ # A bigger backward jump across more than one week/holiday
2712
+ assert_equal(
2713
+ np.busday_offset('2012-01-03', -1, holidays=holidays),
2714
+ np.busday_offset('2012-01-03', -1 - 1))
2715
+ assert_equal(
2716
+ np.busday_offset('2012-01-03', -4, holidays=holidays),
2717
+ np.busday_offset('2012-01-03', -4 - 1))
2718
+ assert_equal(
2719
+ np.busday_offset('2012-01-03', -5, holidays=holidays),
2720
+ np.busday_offset('2012-01-03', -5 - 2))
2721
+ assert_equal(
2722
+ np.busday_offset('2012-01-03', -25, holidays=holidays),
2723
+ np.busday_offset('2012-01-03', -25 - 2))
2724
+ assert_equal(
2725
+ np.busday_offset('2012-01-03', -26, holidays=holidays),
2726
+ np.busday_offset('2012-01-03', -26 - 3))
2727
+ assert_equal(
2728
+ np.busday_offset('2012-01-03', -33, holidays=holidays),
2729
+ np.busday_offset('2012-01-03', -33 - 3))
2730
+ assert_equal(
2731
+ np.busday_offset('2012-01-03', -34, holidays=holidays),
2732
+ np.busday_offset('2012-01-03', -34 - 4))
2733
+ assert_equal(
2734
+ np.busday_offset('2012-01-03', -56, holidays=holidays),
2735
+ np.busday_offset('2012-01-03', -56 - 4))
2736
+ assert_equal(
2737
+ np.busday_offset('2012-01-03', -57, holidays=holidays),
2738
+ np.busday_offset('2012-01-03', -57 - 5))
2739
+ assert_equal(
2740
+ np.busday_offset('2012-01-03', -57, busdaycal=bdd),
2741
+ np.busday_offset('2012-01-03', -57 - 5))
2742
+
2743
+ # Can't supply both a weekmask/holidays and busdaycal
2744
+ assert_raises(ValueError, np.busday_offset, '2012-01-03', -15,
2745
+ weekmask='1111100', busdaycal=bdd)
2746
+ assert_raises(ValueError, np.busday_offset, '2012-01-03', -15,
2747
+ holidays=holidays, busdaycal=bdd)
2748
+
2749
+ # Roll with the holidays
2750
+ assert_equal(
2751
+ np.busday_offset('2011-12-25', 0,
2752
+ roll='forward', holidays=holidays),
2753
+ np.datetime64('2011-12-27'))
2754
+ assert_equal(
2755
+ np.busday_offset('2011-12-26', 0,
2756
+ roll='forward', holidays=holidays),
2757
+ np.datetime64('2011-12-27'))
2758
+ assert_equal(
2759
+ np.busday_offset('2011-12-26', 0,
2760
+ roll='backward', holidays=holidays),
2761
+ np.datetime64('2011-12-23'))
2762
+ assert_equal(
2763
+ np.busday_offset('2012-02-27', 0,
2764
+ roll='modifiedfollowing',
2765
+ holidays=['2012-02-27', '2012-02-26', '2012-02-28',
2766
+ '2012-03-01', '2012-02-29']),
2767
+ np.datetime64('2012-02-24'))
2768
+ assert_equal(
2769
+ np.busday_offset('2012-03-06', 0,
2770
+ roll='modifiedpreceding',
2771
+ holidays=['2012-03-02', '2012-03-03', '2012-03-01',
2772
+ '2012-03-05', '2012-03-07', '2012-03-06']),
2773
+ np.datetime64('2012-03-08'))
2774
+
2775
+ def test_datetime_busday_holidays_count(self):
2776
+ holidays = ['2011-01-01', '2011-10-10', '2011-11-11', '2011-11-24',
2777
+ '2011-12-25', '2011-05-30', '2011-02-21', '2011-01-17',
2778
+ '2011-12-26', '2012-01-02', '2011-02-21', '2011-05-30',
2779
+ '2011-07-01', '2011-07-04', '2011-09-05', '2011-10-10']
2780
+ bdd = np.busdaycalendar(weekmask='1111100', holidays=holidays)
2781
+
2782
+ # Validate against busday_offset broadcast against
2783
+ # a range of offsets
2784
+ dates = np.busday_offset('2011-01-01', np.arange(366),
2785
+ roll='forward', busdaycal=bdd)
2786
+ assert_equal(np.busday_count('2011-01-01', dates, busdaycal=bdd),
2787
+ np.arange(366))
2788
+ # Returns negative value when reversed
2789
+ # -1 since the '2011-01-01' is not a busday
2790
+ assert_equal(np.busday_count(dates, '2011-01-01', busdaycal=bdd),
2791
+ -np.arange(366) - 1)
2792
+
2793
+ # 2011-12-31 is a saturday
2794
+ dates = np.busday_offset('2011-12-31', -np.arange(366),
2795
+ roll='forward', busdaycal=bdd)
2796
+ # only the first generated date is in the future of 2011-12-31
2797
+ expected = np.arange(366)
2798
+ expected[0] = -1
2799
+ assert_equal(np.busday_count(dates, '2011-12-31', busdaycal=bdd),
2800
+ expected)
2801
+ # Returns negative value when reversed
2802
+ expected = -np.arange(366) + 1
2803
+ expected[0] = 0
2804
+ assert_equal(np.busday_count('2011-12-31', dates, busdaycal=bdd),
2805
+ expected)
2806
+
2807
+ # Can't supply both a weekmask/holidays and busdaycal
2808
+ assert_raises(ValueError, np.busday_offset, '2012-01-03', '2012-02-03',
2809
+ weekmask='1111100', busdaycal=bdd)
2810
+ assert_raises(ValueError, np.busday_offset, '2012-01-03', '2012-02-03',
2811
+ holidays=holidays, busdaycal=bdd)
2812
+
2813
+ # Number of Mondays in March 2011
2814
+ assert_equal(np.busday_count('2011-03', '2011-04', weekmask='Mon'), 4)
2815
+ # Returns negative value when reversed
2816
+ assert_equal(np.busday_count('2011-04', '2011-03', weekmask='Mon'), -4)
2817
+
2818
+ sunday = np.datetime64('2023-03-05')
2819
+ monday = sunday + np.timedelta64(1, 'D')
2820
+ friday = sunday + np.timedelta64(5, 'D')
2821
+ saturday = sunday + np.timedelta64(6, 'D')
2822
+ assert_equal(np.busday_count(sunday, monday), 0)
2823
+ assert_equal(np.busday_count(monday, sunday), -1)
2824
+
2825
+ assert_equal(np.busday_count(friday, saturday), 1)
2826
+ assert_equal(np.busday_count(saturday, friday), 0)
2827
+
2828
+ def test_datetime_is_busday(self):
2829
+ holidays = ['2011-01-01', '2011-10-10', '2011-11-11', '2011-11-24',
2830
+ '2011-12-25', '2011-05-30', '2011-02-21', '2011-01-17',
2831
+ '2011-12-26', '2012-01-02', '2011-02-21', '2011-05-30',
2832
+ '2011-07-01', '2011-07-04', '2011-09-05', '2011-10-10',
2833
+ 'NaT']
2834
+ bdd = np.busdaycalendar(weekmask='1111100', holidays=holidays)
2835
+
2836
+ # Weekend/weekday tests
2837
+ assert_equal(np.is_busday('2011-01-01'), False)
2838
+ assert_equal(np.is_busday('2011-01-02'), False)
2839
+ assert_equal(np.is_busday('2011-01-03'), True)
2840
+
2841
+ # All the holidays are not business days
2842
+ assert_equal(np.is_busday(holidays, busdaycal=bdd),
2843
+ np.zeros(len(holidays), dtype='?'))
2844
+
2845
+ def test_datetime_y2038(self):
2846
+ msg = "no explicit representation of timezones available for " \
2847
+ "np.datetime64"
2848
+ # Test parsing on either side of the Y2038 boundary
2849
+ a = np.datetime64('2038-01-19T03:14:07')
2850
+ assert_equal(a.view(np.int64), 2**31 - 1)
2851
+ a = np.datetime64('2038-01-19T03:14:08')
2852
+ assert_equal(a.view(np.int64), 2**31)
2853
+
2854
+ # Test parsing on either side of the Y2038 boundary with
2855
+ # a manually specified timezone offset
2856
+ with pytest.warns(UserWarning, match=msg):
2857
+ a = np.datetime64('2038-01-19T04:14:07+0100')
2858
+ assert_equal(a.view(np.int64), 2**31 - 1)
2859
+ with pytest.warns(UserWarning, match=msg):
2860
+ a = np.datetime64('2038-01-19T04:14:08+0100')
2861
+ assert_equal(a.view(np.int64), 2**31)
2862
+
2863
+ # Test parsing a date after Y2038
2864
+ a = np.datetime64('2038-01-20T13:21:14')
2865
+ assert_equal(str(a), '2038-01-20T13:21:14')
2866
+
2867
+ def test_isnat(self):
2868
+ assert_(np.isnat(np.datetime64('NaT', 'ms')))
2869
+ assert_(np.isnat(np.datetime64('NaT', 'ns')))
2870
+ assert_(not np.isnat(np.datetime64('2038-01-19T03:14:07')))
2871
+
2872
+ assert_(np.isnat(np.timedelta64('NaT', "ms")))
2873
+ assert_(not np.isnat(np.timedelta64(34, "ms")))
2874
+
2875
+ res = np.array([False, False, True])
2876
+ for unit in ['Y', 'M', 'W', 'D',
2877
+ 'h', 'm', 's', 'ms', 'us',
2878
+ 'ns', 'ps', 'fs', 'as']:
2879
+ arr = np.array([123, -321, "NaT"], dtype=f'<datetime64[{unit}]')
2880
+ assert_equal(np.isnat(arr), res)
2881
+ arr = np.array([123, -321, "NaT"], dtype=f'>datetime64[{unit}]')
2882
+ assert_equal(np.isnat(arr), res)
2883
+ arr = np.array([123, -321, "NaT"], dtype=f'<timedelta64[{unit}]')
2884
+ assert_equal(np.isnat(arr), res)
2885
+ arr = np.array([123, -321, "NaT"], dtype=f'>timedelta64[{unit}]')
2886
+ assert_equal(np.isnat(arr), res)
2887
+
2888
+ def test_isnat_error(self):
2889
+ # Test that only datetime dtype arrays are accepted
2890
+ for t in np.typecodes["All"]:
2891
+ if t in np.typecodes["Datetime"]:
2892
+ continue
2893
+ assert_raises(TypeError, np.isnat, np.zeros(10, t))
2894
+
2895
+ def test_isfinite_scalar(self):
2896
+ assert_(not np.isfinite(np.datetime64('NaT', 'ms')))
2897
+ assert_(not np.isfinite(np.datetime64('NaT', 'ns')))
2898
+ assert_(np.isfinite(np.datetime64('2038-01-19T03:14:07')))
2899
+
2900
+ assert_(not np.isfinite(np.timedelta64('NaT', "ms")))
2901
+ assert_(np.isfinite(np.timedelta64(34, "ms")))
2902
+
2903
+ @pytest.mark.parametrize('unit', ['Y', 'M', 'W', 'D', 'h', 'm', 's', 'ms',
2904
+ 'us', 'ns', 'ps', 'fs', 'as'])
2905
+ @pytest.mark.parametrize('dstr', ['<datetime64[%s]', '>datetime64[%s]',
2906
+ '<timedelta64[%s]', '>timedelta64[%s]'])
2907
+ def test_isfinite_isinf_isnan_units(self, unit, dstr):
2908
+ '''check isfinite, isinf, isnan for all units of <M, >M, <m, >m dtypes
2909
+ '''
2910
+ arr_val = [123, -321, "NaT"]
2911
+ arr = np.array(arr_val, dtype=(dstr % unit))
2912
+ pos = np.array([True, True, False])
2913
+ neg = np.array([False, False, True])
2914
+ false = np.array([False, False, False])
2915
+ assert_equal(np.isfinite(arr), pos)
2916
+ assert_equal(np.isinf(arr), false)
2917
+ assert_equal(np.isnan(arr), neg)
2918
+
2919
+ def test_assert_equal(self):
2920
+ assert_raises(AssertionError, assert_equal,
2921
+ np.datetime64('nat', 's'), np.timedelta64('nat', 's'))
2922
+
2923
+ def test_corecursive_input(self):
2924
+ # construct a co-recursive list
2925
+ a, b = [], []
2926
+ a.append(b)
2927
+ b.append(a)
2928
+ obj_arr = np.array([None])
2929
+ obj_arr[0] = a
2930
+
2931
+ # At some point this caused a stack overflow (gh-11154). Now raises
2932
+ # ValueError since the nested list cannot be converted to a datetime.
2933
+ assert_raises(ValueError, obj_arr.astype, 'M8')
2934
+ assert_raises(ValueError, obj_arr.astype, 'm8')
2935
+
2936
+ @pytest.mark.parametrize("shape", [(), (1,)])
2937
+ def test_discovery_from_object_array(self, shape):
2938
+ arr = np.array("2020-10-10", dtype=object).reshape(shape)
2939
+ res = np.array("2020-10-10", dtype="M8").reshape(shape)
2940
+ assert res.dtype == np.dtype("M8[D]")
2941
+ assert_equal(arr.astype("M8"), res)
2942
+ arr[...] = np.bytes_("2020-10-10") # try a numpy string type
2943
+ assert_equal(arr.astype("M8"), res)
2944
+ arr = arr.astype("S")
2945
+ assert_equal(arr.astype("S").astype("M8"), res)
2946
+
2947
+ @pytest.mark.parametrize("time_unit", [
2948
+ "Y", "M", "W", "D", "h", "m", "s", "ms", "us", "ns", "ps", "fs", "as",
2949
+ # compound units
2950
+ "10D", "2M",
2951
+ ])
2952
+ def test_limit_symmetry(self, time_unit):
2953
+ """
2954
+ Dates should have symmetric limits around the unix epoch at +/-np.int64
2955
+ """
2956
+ epoch = np.datetime64(0, time_unit)
2957
+ latest = np.datetime64(np.iinfo(np.int64).max, time_unit)
2958
+ earliest = np.datetime64(-np.iinfo(np.int64).max, time_unit)
2959
+
2960
+ # above should not have overflowed
2961
+ assert earliest < epoch < latest
2962
+
2963
+ @pytest.mark.parametrize("time_unit", [
2964
+ "Y", "M",
2965
+ pytest.param("W", marks=pytest.mark.xfail(reason="gh-13197")),
2966
+ "D", "h", "m",
2967
+ "s", "ms", "us", "ns", "ps", "fs", "as",
2968
+ pytest.param("10D", marks=pytest.mark.xfail(reason="similar to gh-13197")),
2969
+ ])
2970
+ @pytest.mark.parametrize("sign", [-1, 1])
2971
+ def test_limit_str_roundtrip(self, time_unit, sign):
2972
+ """
2973
+ Limits should roundtrip when converted to strings.
2974
+
2975
+ This tests the conversion to and from npy_datetimestruct.
2976
+ """
2977
+ # TODO: add absolute (gold standard) time span limit strings
2978
+ limit = np.datetime64(np.iinfo(np.int64).max * sign, time_unit)
2979
+
2980
+ # Convert to string and back. Explicit unit needed since the day and
2981
+ # week reprs are not distinguishable.
2982
+ limit_via_str = np.datetime64(str(limit), time_unit)
2983
+ assert limit_via_str == limit
2984
+
2985
+ @pytest.mark.parametrize("days,expected", [
2986
+ # Fast-path lower boundary (Neri-Schneider range starts at -12699422)
2987
+ (-12699422, "-32800-03-01"),
2988
+ (-12699421, "-32800-03-02"),
2989
+ # Fast-path upper boundary (Neri-Schneider range ends at 1061042401)
2990
+ (1061042400, "2907005-06-04"),
2991
+ (1061042401, "2907005-06-05"),
2992
+ # Just outside fast-path (fallback)
2993
+ (-12699423, "-32800-02-29"),
2994
+ (1061042402, "2907005-06-06"),
2995
+ # Typical dates near epoch for sanity
2996
+ (0, "1970-01-01"),
2997
+ (-1, "1969-12-31"),
2998
+ (1, "1970-01-02"),
2999
+ # Leap year boundaries
3000
+ (10957, "2000-01-01"),
3001
+ (11016, "2000-02-29"), # 2000 is a leap year
3002
+ (11017, "2000-03-01"),
3003
+ (-25567, "1900-01-01"), # 1900 is not a leap year
3004
+ ])
3005
+ def test_days_to_date_roundtrip(self, days, expected):
3006
+ """Test the calendar conversion at Neri-Schneider algorithm boundaries
3007
+ and typical dates, verifying both the fast-path and fallback."""
3008
+ dt = np.datetime64(days, "D")
3009
+ assert str(dt) == expected
3010
+ # roundtrip back
3011
+ assert dt == np.datetime64(expected, "D")
3012
+
3013
+ def test_cast_to_truncated_string_doesnt_overflow(self):
3014
+ a = np.array([1, -2, 1], dtype='timedelta64[D]')
3015
+ assert_array_equal(a.astype('U1'), ['1', '-', '1'])
3016
+
3017
+ def test_datetime_hash_nat(self):
3018
+ with pytest.warns(
3019
+ DeprecationWarning,
3020
+ match=self.generic_unit_deprecation_message
3021
+ ):
3022
+ nat1 = np.datetime64()
3023
+ nat2 = np.datetime64()
3024
+ assert nat1 is not nat2
3025
+ assert nat1 != nat2
3026
+ assert hash(nat1) != hash(nat2)
3027
+
3028
+ @pytest.mark.parametrize('unit', ('Y', 'M', 'W', 'D', 'h', 'm', 's', 'ms', 'us'))
3029
+ def test_datetime_hash_weeks(self, unit):
3030
+ dt = np.datetime64(2348, 'W') # 2015-01-01
3031
+ dt2 = np.datetime64(dt, unit)
3032
+ _assert_equal_hash(dt, dt2)
3033
+
3034
+ dt3 = np.datetime64(int(dt2.astype(int)) + 1, unit)
3035
+ assert hash(dt) != hash(dt3) # doesn't collide
3036
+
3037
+ @pytest.mark.parametrize('unit', ('h', 'm', 's', 'ms', 'us'))
3038
+ def test_datetime_hash_weeks_vs_pydatetime(self, unit):
3039
+ dt = np.datetime64(2348, 'W') # 2015-01-01
3040
+ dt2 = np.datetime64(dt, unit)
3041
+ pydt = dt2.astype(datetime.datetime)
3042
+ assert isinstance(pydt, datetime.datetime)
3043
+ _assert_equal_hash(pydt, dt2)
3044
+
3045
+ @pytest.mark.parametrize('unit', ('Y', 'M', 'W', 'D', 'h', 'm', 's', 'ms', 'us'))
3046
+ def test_datetime_hash_big_negative(self, unit):
3047
+ dt = np.datetime64(-102894, 'W') # -002-01-01
3048
+ dt2 = np.datetime64(dt, unit)
3049
+ _assert_equal_hash(dt, dt2)
3050
+
3051
+ # can only go down to "fs" before integer overflow
3052
+ @pytest.mark.parametrize('unit', ('m', 's', 'ms', 'us', 'ns', 'ps', 'fs'))
3053
+ def test_datetime_hash_minutes(self, unit):
3054
+ dt = np.datetime64(3, 'm')
3055
+ dt2 = np.datetime64(dt, unit)
3056
+ _assert_equal_hash(dt, dt2)
3057
+
3058
+ @pytest.mark.parametrize('unit', ('ns', 'ps', 'fs', 'as'))
3059
+ def test_datetime_hash_ns(self, unit):
3060
+ dt = np.datetime64(3, 'ns')
3061
+ dt2 = np.datetime64(dt, unit)
3062
+ _assert_equal_hash(dt, dt2)
3063
+
3064
+ dt3 = np.datetime64(int(dt2.astype(int)) + 1, unit)
3065
+ assert hash(dt) != hash(dt3) # doesn't collide
3066
+
3067
+ @pytest.mark.parametrize('wk', range(500000, 500010)) # 11552-09-04
3068
+ @pytest.mark.parametrize('unit', ('W', 'D', 'h', 'm', 's', 'ms', 'us'))
3069
+ def test_datetime_hash_big_positive(self, wk, unit):
3070
+ dt = np.datetime64(wk, 'W')
3071
+ dt2 = np.datetime64(dt, unit)
3072
+ _assert_equal_hash(dt, dt2)
3073
+
3074
+ def test_timedelta_hash_generic(self):
3075
+ with pytest.warns(
3076
+ DeprecationWarning,
3077
+ match=self.generic_unit_deprecation_message,
3078
+ ):
3079
+ assert_raises(ValueError, hash, np.timedelta64(123)) # generic
3080
+
3081
+ @pytest.mark.parametrize('unit', ('Y', 'M'))
3082
+ def test_timedelta_hash_year_month(self, unit):
3083
+ td = np.timedelta64(45, 'Y')
3084
+ td2 = np.timedelta64(td, unit)
3085
+ _assert_equal_hash(td, td2)
3086
+
3087
+ @pytest.mark.parametrize('unit', ('W', 'D', 'h', 'm', 's', 'ms', 'us'))
3088
+ def test_timedelta_hash_weeks(self, unit):
3089
+ td = np.timedelta64(10, 'W')
3090
+ td2 = np.timedelta64(td, unit)
3091
+ _assert_equal_hash(td, td2)
3092
+
3093
+ td3 = np.timedelta64(int(td2.astype(int)) + 1, unit)
3094
+ assert hash(td) != hash(td3) # doesn't collide
3095
+
3096
+ @pytest.mark.parametrize('unit', ('W', 'D', 'h', 'm', 's', 'ms', 'us'))
3097
+ def test_timedelta_hash_weeks_vs_pydelta(self, unit):
3098
+ td = np.timedelta64(10, 'W')
3099
+ td2 = np.timedelta64(td, unit)
3100
+ pytd = td2.astype(datetime.timedelta)
3101
+ assert isinstance(pytd, datetime.timedelta)
3102
+ _assert_equal_hash(pytd, td2)
3103
+
3104
+ @pytest.mark.parametrize('unit', ('ms', 'us', 'ns', 'ps', 'fs', 'as'))
3105
+ def test_timedelta_hash_ms(self, unit):
3106
+ td = np.timedelta64(3, 'ms')
3107
+ td2 = np.timedelta64(td, unit)
3108
+ _assert_equal_hash(td, td2)
3109
+
3110
+ td3 = np.timedelta64(int(td2.astype(int)) + 1, unit)
3111
+ assert hash(td) != hash(td3) # doesn't collide
3112
+
3113
+ @pytest.mark.parametrize('wk', range(500000, 500010))
3114
+ @pytest.mark.parametrize('unit', ('W', 'D', 'h', 'm', 's', 'ms', 'us'))
3115
+ def test_timedelta_hash_big_positive(self, wk, unit):
3116
+ td = np.timedelta64(wk, 'W')
3117
+ td2 = np.timedelta64(td, unit)
3118
+ _assert_equal_hash(td, td2)
3119
+
3120
+ @pytest.mark.parametrize(
3121
+ "inputs, divisor, expected",
3122
+ [
3123
+ (
3124
+ np.array(
3125
+ [datetime.timedelta(seconds=20), datetime.timedelta(days=2)],
3126
+ dtype="object",
3127
+ ),
3128
+ np.int64(2),
3129
+ np.array(
3130
+ [datetime.timedelta(seconds=10), datetime.timedelta(days=1)],
3131
+ dtype="object",
3132
+ ),
3133
+ ),
3134
+ (
3135
+ np.array(
3136
+ [datetime.timedelta(seconds=20), datetime.timedelta(days=2)],
3137
+ dtype="object",
3138
+ ),
3139
+ np.timedelta64(2, "s"),
3140
+ np.array(
3141
+ [10.0, 24.0 * 60.0 * 60.0],
3142
+ dtype="object",
3143
+ ),
3144
+ ),
3145
+ (
3146
+ datetime.timedelta(seconds=2),
3147
+ np.array(
3148
+ [datetime.timedelta(seconds=20), datetime.timedelta(days=2)],
3149
+ dtype="object",
3150
+ ),
3151
+ np.array(
3152
+ [1.0 / 10.0, 1.0 / (24.0 * 60.0 * 60.0)],
3153
+ dtype="object",
3154
+ ),
3155
+ ),
3156
+ ],
3157
+ )
3158
+ def test_true_divide_object_by_timedelta(
3159
+ self,
3160
+ inputs: np.ndarray | type[np.generic],
3161
+ divisor: np.ndarray | type[np.generic],
3162
+ expected: np.ndarray,
3163
+ ):
3164
+ # gh-30025
3165
+ results = inputs / divisor
3166
+ assert_array_equal(results, expected)
3167
+
3168
+ @pytest.mark.parametrize(
3169
+ "atol", [np.timedelta64(1, "s"), np.timedelta64(1, "ms")]
3170
+ )
3171
+ def test_assert_all_close_with_timedelta_atol(
3172
+ self, atol: np.timedelta64 | datetime.timedelta
3173
+ ):
3174
+ # gh-30382
3175
+ a = np.array([1, 2], dtype="m8[s]")
3176
+ b = np.array([3, 4], dtype="m8[s]")
3177
+ with pytest.raises(AssertionError):
3178
+ np.testing.assert_allclose(a, b, atol=atol)
3179
+
3180
+ class TestDateTimeData:
3181
+
3182
+ def test_basic(self):
3183
+ a = np.array(['1980-03-23'], dtype=np.datetime64)
3184
+ assert_equal(np.datetime_data(a.dtype), ('D', 1))
3185
+
3186
+ def test_bytes(self):
3187
+ # byte units are converted to unicode
3188
+ dt = np.datetime64('2000', (b'ms', 5))
3189
+ assert np.datetime_data(dt.dtype) == ('ms', 5)
3190
+
3191
+ dt = np.datetime64('2000', b'5ms')
3192
+ assert np.datetime_data(dt.dtype) == ('ms', 5)
3193
+
3194
+ def test_non_ascii(self):
3195
+ # μs is normalized to μ
3196
+ dt = np.datetime64('2000', ('μs', 5))
3197
+ assert np.datetime_data(dt.dtype) == ('us', 5)
3198
+
3199
+ dt = np.datetime64('2000', '5μs')
3200
+ assert np.datetime_data(dt.dtype) == ('us', 5)
3201
+
3202
+
3203
+ def test_comparisons_return_not_implemented():
3204
+ # GH#17017
3205
+
3206
+ class custom:
3207
+ __array_priority__ = 10000
3208
+
3209
+ obj = custom()
3210
+
3211
+ dt = np.datetime64('2000', 'ns')
3212
+ td = dt - dt
3213
+
3214
+ for item in [dt, td]:
3215
+ assert item.__eq__(obj) is NotImplemented
3216
+ assert item.__ne__(obj) is NotImplemented
3217
+ assert item.__le__(obj) is NotImplemented
3218
+ assert item.__lt__(obj) is NotImplemented
3219
+ assert item.__ge__(obj) is NotImplemented
3220
+ assert item.__gt__(obj) is NotImplemented