@@ -640,6 +640,61 @@ 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
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' , 'us' , 'ms' , 's' , 'h' , 'm' , 'D' ])
670+ def test_astype_to_timedelta_unit (self , unit ):
671+ # tests all units from timedelta origination
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" , ['ns' , 'us' , 'ms' , 's' , 'h' , 'm' , 'D' ])
682+ def test_astype_to_incorrect_datetimelike (self , unit ):
683+ # trying to astype a m to a M, or vice-versa
684+ # gh-19176
685+ dtype = "M8[{}]" .format (unit )
686+ other = "m8[{}]" .format (unit )
687+
688+ with pytest .raises (TypeError ):
689+ arr = np .array ([[1 , 2 , 3 ]], dtype = dtype )
690+ df = DataFrame (arr )
691+ df .astype (other )
692+
693+ with pytest .raises (TypeError ):
694+ arr = np .array ([[1 , 2 , 3 ]], dtype = other )
695+ df = DataFrame (arr )
696+ df .astype (dtype )
697+
643698 def test_timedeltas (self ):
644699 df = DataFrame (dict (A = Series (date_range ('2012-1-1' , periods = 3 ,
645700 freq = 'D' )),
0 commit comments