Pandas: Return Hour from Datetime Column Directly

前端 未结 7 1744
我在风中等你
我在风中等你 2020-11-30 03:19

Assume I have a DataFrame sales of timestamp values:

timestamp               sales_office
2014-01-01 09:01:00     Cincinnati
2014-01-01 09:11:00         


        
相关标签:
7条回答
  • 2020-11-30 03:19

    Since the quickest, shortest answer is in a comment (from Jeff) and has a typo, here it is corrected and in full:

    sales['time_hour'] = pd.DatetimeIndex(sales['timestamp']).hour
    
    0 讨论(0)
  • 2020-11-30 03:27

    You can try this:

    sales['time_hour'] = pd.to_datetime(sales['timestamp']).dt.hour
    
    0 讨论(0)
  • 2020-11-30 03:32

    For posterity: as of 0.15.0, there is a handy .dt accessor you can use to pull such values from a datetime/period series (in the above case, just sales.timestamp.dt.hour!

    0 讨论(0)
  • 2020-11-30 03:32

    You can use a lambda expression, e.g:

    sales['time_hour'] = sales.timestamp.apply(lambda x: x.hour)
    
    0 讨论(0)
  • 2020-11-30 03:36

    Now we can use:

    sales['time_hour'] = sales['timestamp'].apply(lambda x: x.hour)
    
    0 讨论(0)
  • 2020-11-30 03:39

    Here is a simple solution:

    import pandas as pd
    # convert the timestamp column to datetime
    df['timestamp'] = pd.to_datetime(df['timestamp'])
    
    # extract hour from the timestamp column to create an time_hour column
    df['time_hour'] = df['timestamp'].dt.hour
    
    0 讨论(0)
提交回复
热议问题