1

Here's my data:

 device_create_at               
136 2014-08-27 17:29:23            
245 2015-09-06 15:46:00            
257 2014-09-29 22:26:34            
258 2014-11-05 13:02:18    

Here's my expected output

  device_create_at                device_create_hour
136 2014-08-27 17:29:23            2014-08-27 17
245 2015-09-06 15:46:00            2015-09-06 15
257 2014-09-29 22:26:34            2014-09-29 22
258 2014-11-05 13:02:18            2014-11-05 13

As far as I know, pandas.Series.dt.strftime can do weekly mapping, the code is like this

sheet2['device_create_week'] = sheet2['device_create_at'].dt.strftime('%Y-%V')

They use %V for week not %W, I try to make this hourly

sheet2['device_create_hour'] = sheet2['device_create_at'].dt.strftime('%Y-%M-%D-%H')

That is doeesn't work

Nabih Ibrahim Bawazir
  • 631
  • 2
  • 15
  • 27

1 Answers1

3
s = df.device_create_at.dt.strftime('%Y-%m-%d %H')
print(s)
136    2014-08-27 17
245    2015-09-06 15
257    2014-09-29 22
258    2014-11-05 13
Name: device_create_at, dtype: object

Note that the format is %Y-%m-%d %H with small m and small d.

For more info about all directives eg: %M,%m, you can find it in the python documentation.

Firas Omrane
  • 894
  • 1
  • 14
  • 21
cs95
  • 379,657
  • 97
  • 704
  • 746
  • OKm my suggestion is right. The problem on my data, error message `Can only use .dt accessor with datetimelike values` – Nabih Ibrahim Bawazir Oct 18 '17 at 05:20
  • @NabihIbrahimBawazir The fundamental assumption with this method was that your column is a datetime column. If it's not, you'll need to use `pd.to_datetime` and convert it: `df.device_create_at = pd.to_datetime(df.device_create_at)` – cs95 Oct 18 '17 at 05:21
  • yes, I already read this here https://stackoverflow.com/questions/33365055/attributeerror-can-only-use-dt-accessor-with-datetimelike-values , and try `pd.to_datetime(df['device_create_at'], coerce=True)` and no argument call coerce – Nabih Ibrahim Bawazir Oct 18 '17 at 05:24
  • @NabihIbrahimBawazir It's `pd.to_datetime(df['Date'], errors='coerce')` in newer versions. – cs95 Oct 18 '17 at 05:25