0

Hi my use case is I have dynamic names of datetime field and date will be some thing like unix timestamp . so every time there could be different column name and there can be multiple date filed . so how I can do this ? for now if I do hardcode for column name this works for me

df['date'] = pandas.to_datetime(df['date'], unit='s')

but not sure how I can make this for dynamic names and multiple fields with pandas

1 Answers1

0

As suggested on my comment, you can try to convert all columns as DatetimeIndex then just keep one where conversion succeeded?

# Inspired from @mozway, https://stackoverflow.com/a/75106101/15239951
def find_datetime_col(df):
    mask = df.astype(str).apply(pd.to_datetime, errors='coerce').notna()
    return mask.mean().idxmax()

col = find_datetime_col(df)
print(col)

# Output
Heading 1

Input dataframe:

>>> df
   Heading 1  Heading 2  Heading 3  Heading 4
0 2023-01-01         34         12         34
1 2023-01-02         42         99         42
2 2023-01-03         42         99         42
3 2023-01-04         42         99         42
Corralien
  • 109,409
  • 8
  • 28
  • 52