@@ -2625,3 +2625,30 @@ def test_pivot_table_empty_dataframe_correct_index(self):
26252625
26262626 expected = Index ([], dtype = "object" , name = "b" )
26272627 tm .assert_index_equal (pivot .columns , expected )
2628+
2629+ def test_pivot_table_handles_explicit_datetime_types (self ):
2630+ # GH#43574
2631+ df = DataFrame (
2632+ [
2633+ {"a" : "x" , "date_str" : "2023-01-01" , "amount" : 1 },
2634+ {"a" : "y" , "date_str" : "2023-01-02" , "amount" : 2 },
2635+ {"a" : "z" , "date_str" : "2023-01-03" , "amount" : 3 },
2636+ ]
2637+ )
2638+ df ["date" ] = pd .to_datetime (df ["date_str" ])
2639+
2640+ with tm .assert_produces_warning (False ):
2641+ pivot = df .pivot_table (
2642+ index = ["a" , "date" ], values = ["amount" ], aggfunc = "sum" , margins = True
2643+ )
2644+
2645+ expected = MultiIndex .from_tuples (
2646+ [
2647+ ("x" , datetime .strptime ("2023-01-01 00:00:00" , "%Y-%m-%d %H:%M:%S" )),
2648+ ("y" , datetime .strptime ("2023-01-02 00:00:00" , "%Y-%m-%d %H:%M:%S" )),
2649+ ("z" , datetime .strptime ("2023-01-03 00:00:00" , "%Y-%m-%d %H:%M:%S" )),
2650+ ("All" , "" ),
2651+ ],
2652+ names = ["a" , "date" ],
2653+ )
2654+ tm .assert_index_equal (pivot .index , expected )
0 commit comments