0
votes

I try to extract hour from the timestamp : I have a dataframe called df_no_missing :

df_no_missing.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 34673 entries, 1 to 43228
Data columns (total 8 columns):
TIMESTAMP        34673 non-null object
P_ACT_KW         34673 non-null float64
PERIODE_TARIF    34673 non-null object
P_SOUSCR         34673 non-null float64
SITE             34673 non-null object
TARIF            34673 non-null object
depassement      34673 non-null float64
date             34673 non-null int64
dtypes: float64(3), int64(1), object(4)
memory usage: 2.4+ MB

This is my code :

from datetime import datetime,timedelta
mytime = datetime.strptime(df_no_missing["TIMESTAMP"],"%d/%m/%Y %H:%M")
print (mytime.day)
print (mytime.hour)

I get this error :

in () 1 df_no_missing.info() 2 from datetime import datetime,timedelta ----> 3 mytime = datetime.strptime(df_no_missing["TIMESTAMP"],"%d/%m/%Y %H:%M") 4 print (mytime.day) 5 print (mytime.hour)

TypeError: strptime() argument 1 must be str, not Series

1
df_no_missing["TIMESTAMP"] returns the whole column, you can't use it in this context. What do you expect the value of mytime to be? - DeepSpace
This seems invalid, the column dtype is object suggesting it's string, you haven't displayed what the current format is but can you try df_no_missing["TIMESTAMP"] = pd.to_datetime(df_no_missing["TIMESTAMP"]) to convert to datetime after which you can do df_no_missing["TIMESTAMP"].dt.day and df_no_missing["TIMESTAMP"].dt.hour - EdChum

1 Answers

0
votes

you would probably want to use datetime.strptime on a single entry rather than on the dataframe object itself? Try something like:

for data in df_no_missing["TIMESTAMP"]:
    mytime = datetime.strptime(data,"%d/%m/%Y %H:%M")
    print (mytime.day)
    print (mytime.hour)