0

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!

Mei Tei
  • 55
  • 1
  • 7
  • please show us a sample of `traindf`. Here's an excellent post detailing how to make a good reproducible pandas question: https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples – Haleemur Ali Jun 10 '19 at 03:13

1 Answers1

1

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.

seanswe
  • 311
  • 2
  • 7
  • you may need to convert it to int first : traindf['unix_timestamp_of_request_utc'] = traindf['unix_timestamp_of_request_utc'].astype(int) then the apply – R Chang Aug 23 '22 at 02:29