Easiest way to determine whether column in pandas Dataframe contains DATE or DATETIME information

Viewed 887

I have the following DF:

  col1         col2
1 2017-01-03   2018-03-30 08:01:32
2 2017-01-04   2018-03-30 08:02:32

If I do df.dtypes, I get get the following output:

col1    datetime64[ns]
col2    datetime64[ns]
dtype: object

Howeverm col1 contains Only Date information (DATE), whereas col2 contains both date and time information (DATETIME).

Whats the easiest way to determine wheter a column contains DATE or DATETIME information?

Data generation:

import pandas as pd

# Generate the df
col1 = ["2017-01-03", "2017-01-04"]
col2 = ["2018-03-30 08:01:32", "2018-03-30 08:02:32"]

df = pd.DataFrame({"col1": col1, "col2": col2})

df["col1"] = pd.to_datetime(df["col1"])
df["col2"] = pd.to_datetime(df["col2"])
2 Answers

According to this SO Question, the following function could do the job:

def check_col(col):
    try:
        dt = pd.to_datetime(df[col])
        if (dt.dt.floor('d') == dt).all():
            return('Its a DATE field')
        else:
            return('Its a DATETIME field')
    except:
        return("could not parse to pandas datetime")

However, isn't there a more straightforward way?

You can try this:

def col_has_time(col):
    dt = pd.to_datetime(df[col])
    return (dt.hour == 0).all()
Related