pandas.DataFrame.to_timestamp#
- DataFrame.to_timestamp(freq=None, how='start', axis=0, copy=<no_default>)[source]#
Cast PeriodIndex to DatetimeIndex, by default at beginning of period.
This can be changed to the end of the period, by specifying how=”e”.
- Parameters:
- freqstr or DateOffset, optional
Target frequency. By default the result is exactly the start (or end) of each period. With
how="start", the result is the start ofasfreq(freq, how="start"), except that afreqcoarser than daily gives midnight on that period’s last day, soto_timestamp("M")gives month-end dates. Withhow="end",freqonly affects the resolution (‘ns’ gives nanosecond unit).- how{‘start’, ‘end’, ‘s’, ‘e’}, default ‘start’
Convention for converting period to timestamp; start of period vs. end. Case-insensitive.
- axis{0 or ‘index’, 1 or ‘columns’}, default 0
The axis to convert (the index by default).
- copybool, default False
This keyword is now ignored; changing its value will have no impact on the method.
Deprecated since version 3.0.0: This keyword is ignored and will be removed in pandas 4.0. Since pandas 3.0, this method always returns a new object using a lazy copy mechanism that defers copies until necessary (Copy-on-Write). See the user guide on Copy-on-Write for more details.
- Returns:
- DataFrame with DatetimeIndex
DataFrame with the PeriodIndex cast to DatetimeIndex.
See also
DataFrame.to_periodInverse method to cast DatetimeIndex to PeriodIndex.
Series.to_timestampEquivalent method for Series.
Examples
>>> idx = pd.PeriodIndex(["2023", "2024"], freq="Y") >>> d = {"col1": [1, 2], "col2": [3, 4]} >>> df1 = pd.DataFrame(data=d, index=idx) >>> df1 col1 col2 2023 1 3 2024 2 4
The resulting timestamps will be at the beginning of the year in this case
>>> df1 = df1.to_timestamp() >>> df1 col1 col2 2023-01-01 1 3 2024-01-01 2 4 >>> df1.index DatetimeIndex(['2023-01-01', '2024-01-01'], dtype='datetime64[us]', freq=None)
With
freq="M", each timestamp is the last day of the period’s first month>>> df2 = pd.DataFrame(data=d, index=idx) >>> df2 = df2.to_timestamp(freq="M") >>> df2 col1 col2 2023-01-31 1 3 2024-01-31 2 4 >>> df2.index DatetimeIndex(['2023-01-31', '2024-01-31'], dtype='datetime64[us]', freq=None)