Search code examples
pythonpandasdataframeunix-timestamp

Is there a function that converts unix timestamps into just the hour variables in a dataframe?


I'm new to python, so this may seem obvious, but I'm trying to replace a column in a dataframe named unix_timestamp with the hours for the specific unix_timestamp. EX: [1326429793] would turn into [4]

I tried using the panda method to_datetime but it doesn't do what I want. I'm currently using the .hour in a few examples I saw online - datetime.utcfromtimestamp(1326429793).hour but when applying it to a dataframe it outputs an error

from datetime import datetime
import pandas as pd
#
traindf['hour'] = datetime.utcfromtimestamp(traindf['unix_timestamp_of_request_utc']).hour

The above code returns the TypeError: cannot convert the series to class 'int'.

Thanks in advance!


Solution

  • You can use apply:

    traindf['hour'] = traindf['unix_timestamp_of_request_utc'].apply(pd.Timestamp.utcfromtimestamp).dt.hour
    

    Also, pd.Timestamp has its own utcfromtimestamp method.