fusionlab.utils.ts_utils.to_dt¶
- fusionlab.utils.ts_utils.to_dt(df, dt_col=None, return_dt_col=False, format=None, error='raise', verbose=0, **kwargs)[source]¶
Converts a given DataFrame’s column or index to datetime format using pandas’
to_datetimefunctionality. This method to_dt handles integer-based columns or index by converting them to string before parsing. It can also return the name of the processed datetime column.- Parameters:
df (
pd.DataFrame) – The input DataFrame that will be converted.dt_col (
str, optional) – The name of the column to convert to datetime. If dt_col is None, then the DataFrame index will be converted.return_dt_col (
bool, defaultFalse) – If True, returns a tuple of the processed DataFrame and the name of the datetime column (or None if the index was converted). If False, returns only the processed DataFrame.format (
str, optional) – Thestrftimeformat to use for parsing the datetime strings. If None, pandas attempts to infer the format automatically.error (
{'raise', 'warn', 'ignore'}, default'raise') – The strategy to handle parsing errors. If ‘raise’, an exception is raised. If ‘warn’, a warning is issued. If ‘ignore’, the original DataFrame is returned unmodified without raising or warning.verbose (
int, default0) – The verbosity level of log messages: * 0 : No messages. * 1 : Basic messages. * 2 : More detailed messages. * 3 : Most verbose messages.**kwargs – Additional keyword arguments passed directly to
pd.to_datetime.
- Returns:
The processed DataFrame with the specified column or index converted to datetime. If return_dt_col is True, a tuple of (processed DataFrame, datetime column name/None) is returned.
- Return type:
pd.DataFrameortuple
Examples
>>> from fusionlab.utils.ts_utils import to_dt >>> import pandas as pd
>>> data = { ... 'Date': ['2021-01-01', '2021-01-02', '2021-01-03'], ... 'Value': [100, 200, 300] ... } >>> df = pd.DataFrame(data) >>> # Convert a column to datetime >>> df_dt = to_dt(df, dt_col='Date') >>> df_dt.info()
>>> # Convert the index to datetime (example index as strings) >>> df_idx = df.set_index('Date') >>> df_idx_converted = to_dt(df_idx) >>> df_idx_converted.index
Notes
Internally, to_dt calls
pd.to_datetimeto perform the actual conversion. If an integer column or index is supplied, it is first cast to string and then parsed as datetime. This can be useful when timestamps are stored as integer values representing YYYYMMDD or similar formats.\[\text{Let } X \in \{\text{column, index}\}, \quad X_{\text{dt}} = pd.to\_datetime(X, \ldots)\]Here, \(X_{\text{dt}}\) is the converted datetime representation. If
dt_colis not provided, the index of the DataFrame is converted.See also
pandas.to_datetimePandas function for converting objects to datetime.
pandas.DataFrame.astypeCast object to a specified dtype.
References