Pandas DataFrame | to_timestamp method
Start your free 7-days trial now!
Pandas DataFrame.to_timestamp(~) method converts the row index or column index to DatetimeIndex.
Parameters
1. freqlink | string | optional
Defaults to the frequency used in PeriodIndex.
2. howlink | string | optional
Whether to use the starting or ending time of PeriodIndex:
Value | Description |
|---|---|
| Use the starting time of the period. |
| Use the ending time of the period. |
By default, how="start".
3. axis | string | optional
Whether to convert the index or column labels:
Axis | Description |
|---|---|
| Converts index to |
| Converts column labels to |
By default, axis=0.
4. copy | boolean | optional
If
True, then a new DataFrame is returned. Modifying this DataFrame will not mutate the source DataFrame, and vice versa.If
False, then no new DataFrame is created - modifying the returned DataFrame will mutate the source DataFrame, and vice versa.
By default, copy=True.
Return Value
A DataFrame with the index or column label converted to DatetimeIndex.
Examples
Basic usage
Consider the following DataFrame:
index_period = pd.PeriodIndex(["2020-12-25"], freq="D")df = pd.DataFrame({"A":[2]}, index=index_period)df
A2020-12-25 2
Here, the index of df is of type PeriodIndex:
df.index
PeriodIndex(['2020-12-25'], dtype='period[D]', freq='D')
To convert the index from PeriodIndex to DatetimeIndex:
df_converted = df.to_timestamp()df_converted
A2020-12-25 2
Now, checking the type of the converted index:
df_converted.index
DatetimeIndex(['2020-12-25'], dtype='datetime64[ns]', freq=None)
We see that index of df_converted is now DatetimeIndex.
Specifying freq
Consider the following DataFrame with a PeriodIndex:
index_period = pd.PeriodIndex(["2020-12-25","2020-12-26","2020-12-27"], freq="D")df = pd.DataFrame({"A":[2,3,4]}, index=index_period)df
A2020-12-25 22020-12-26 32020-12-27 4
Suppose we wanted to strip away information about the day unit. We can do so using the freq parameter like so:
df_converted = df.to_timestamp(freq="M")df_converted
A2020-12-31 22020-12-31 32020-12-31 4
Now, all the day units are set to the end of the month (31).
Just as reference, here's the index of df_converted:
df_converted.index
DatetimeIndex(['2020-12-31', '2020-12-31', '2020-12-31'], dtype='datetime64[ns]', freq=None)
Specifying how
Consider the following DataFrame:
index_period = pd.PeriodIndex(["2020-12-25"], freq="D")df = pd.DataFrame({"A":[2]}, index=index_period)df
A2020-12-25 2
By default, how="s", which means that the start of the period is used:
df.to_timestamp(how="s")
A2020-12-25 2
To use the end of the period, set how="e":
df.to_timestamp(how="e")
A2020-12-25 23:59:59.999999999 2