@@ -640,6 +640,73 @@ def test_astype_categoricaldtype_class_raises(self, cls):
640640 with tm .assert_raises_regex (TypeError , xpr ):
641641 df ['A' ].astype (cls )
642642
643+ @pytest .mark .parametrize ("arr_dtype" , [np .int64 , np .float64 ])
644+ @pytest .mark .parametrize ("dtype" , ["M8" , "m8" ])
645+ @pytest .mark .parametrize ("unit" , ['ns' , 'us' , 'ms' , 's' , 'h' , 'm' , 'D' ])
646+ def test_astype_to_datetimelike_unit (self , arr_dtype , dtype , unit ):
647+ # tests all units from numeric origination
648+ # gh-19223 / gh-12425
649+ dtype = "{}[{}]" .format (dtype , unit )
650+ arr = np .array ([[1 , 2 , 3 ]], dtype = arr_dtype )
651+ df = DataFrame (arr )
652+ result = df .astype (dtype )
653+ expected = DataFrame (arr .astype (dtype ))
654+
655+ tm .assert_frame_equal (result , expected )
656+
657+ @pytest .mark .parametrize ("unit" , ['ns' , 'us' , 'ms' , 's' , 'h' , 'm' , 'D' ])
658+ def test_astype_to_datetime_unit (self , unit ):
659+ # tests all units from datetime origination
660+ # gh-19223
661+ dtype = "M8[{}]" .format (unit )
662+ arr = np .array ([[1 , 2 , 3 ]], dtype = dtype )
663+ df = DataFrame (arr )
664+ result = df .astype (dtype )
665+ expected = DataFrame (arr .astype (dtype ))
666+
667+ tm .assert_frame_equal (result , expected )
668+
669+ @pytest .mark .parametrize ("unit" , ['ns' ])
670+ def test_astype_to_timedelta_unit_ns (self , unit ):
671+ # preserver the timedelta conversion
672+ # gh-19223
673+ dtype = "m8[{}]" .format (unit )
674+ arr = np .array ([[1 , 2 , 3 ]], dtype = dtype )
675+ df = DataFrame (arr )
676+ result = df .astype (dtype )
677+ expected = DataFrame (arr .astype (dtype ))
678+
679+ tm .assert_frame_equal (result , expected )
680+
681+ @pytest .mark .parametrize ("unit" , ['us' , 'ms' , 's' , 'h' , 'm' , 'D' ])
682+ def test_astype_to_timedelta_unit (self , unit ):
683+ # coerce to float
684+ # gh-19223
685+ dtype = "m8[{}]" .format (unit )
686+ arr = np .array ([[1 , 2 , 3 ]], dtype = dtype )
687+ df = DataFrame (arr )
688+ result = df .astype (dtype )
689+ expected = DataFrame (df .values .astype (dtype ).astype (float ))
690+
691+ tm .assert_frame_equal (result , expected )
692+
693+ @pytest .mark .parametrize ("unit" , ['ns' , 'us' , 'ms' , 's' , 'h' , 'm' , 'D' ])
694+ def test_astype_to_incorrect_datetimelike (self , unit ):
695+ # trying to astype a m to a M, or vice-versa
696+ # gh-19224
697+ dtype = "M8[{}]" .format (unit )
698+ other = "m8[{}]" .format (unit )
699+
700+ with pytest .raises (TypeError ):
701+ arr = np .array ([[1 , 2 , 3 ]], dtype = dtype )
702+ df = DataFrame (arr )
703+ df .astype (other )
704+
705+ with pytest .raises (TypeError ):
706+ arr = np .array ([[1 , 2 , 3 ]], dtype = other )
707+ df = DataFrame (arr )
708+ df .astype (dtype )
709+
643710 def test_timedeltas (self ):
644711 df = DataFrame (dict (A = Series (date_range ('2012-1-1' , periods = 3 ,
645712 freq = 'D' )),
0 commit comments