Code source de geonature.core.imports.checks.dataframe.dates
importpandasaspd
[docs]defconcat_dates(df:pd.DataFrame,datetime_min_col:str,datetime_max_col:str,date_min_col:str,date_max_col:str=None,hour_min_col:str=None,hour_max_col:str=None,):""" Concatenates date and time columns to form datetime columns. Parameters ---------- df : pandas.DataFrame The input DataFrame. datetime_min_col : str The column name for the minimum datetime. datetime_max_col : str The column name for the maximum datetime. date_min_col : str The column name for the minimum date. date_max_col : str, optional The column name for the maximum date. hour_min_col : str, optional The column name for the minimum hour. hour_max_col : str, optional The column name for the maximum hour. """assertdatetime_min_colassertdatetime_max_colassertdate_min_col# date_min is a required fielddate_max_col=date_max_colifdate_max_colelseNonehour_min_col=hour_min_colifhour_min_colelseNonehour_max_col=hour_max_colifhour_max_colelseNonedate_min=df[date_min_col]ifhour_min_colandhour_min_colindf:hour_min=df[hour_min_col].where(df[hour_min_col].notna(),other="00:00:00")ifhour_min_colandhour_min_colindf:df[datetime_min_col]=date_min+" "+hour_minelse:df[datetime_min_col]=date_minifdate_max_colanddate_max_colindf:date_max=df[date_max_col].where(df[date_max_col].notna(),date_min)else:date_max=date_minifhour_max_colandhour_max_colindf:ifdate_max_colanddate_max_colindf:# hour max is set to hour min if date max is none (because date max will be set to date min), else 00:00:00ifhour_min_colandhour_min_colindf:# if hour_max not set, use hour_min if same day (or date_max not set, so same day)hour_max=df[hour_max_col].where(df[hour_max_col].notna(),other=hour_min.where(date_min==date_max,other="00:00:00"),)else:hour_max=df[hour_max_col].where(df[hour_max_col].notna(),other="00:00:00")else:ifhour_min_colandhour_min_colindf:hour_max=df[hour_max_col].where(df[hour_max_col].notna(),other=hour_min)else:hour_max=df[hour_max_col].where(df[hour_max_col].notna(),other="00:00:00")ifhour_max_colandhour_max_colindf:df[datetime_max_col]=date_max+" "+hour_maxelifhour_min_colandhour_min_colindf:df[datetime_max_col]=date_max+" "+hour_minelse:df[datetime_max_col]=date_maxreturn{datetime_min_col,datetime_max_col}