【问题标题】:How to strip a pandas datetime of date, hours and seconds如何剥离日期,小时和秒的熊猫日期时间
【发布时间】:2017-06-16 17:36:32
【问题描述】:

如何从 pandas 日期时间中删除日期、小时和秒,以便只剩下分钟?我有一个格式如下的日期表:

Date
2015-04-18 23:33:58
2015-04-19 14:32:08
2015-04-20 18:42:44
2015-04-20 21:41:19

我想要:

Date
33
32
42
41

我尝试使用的代码是:

fiveMin['Date'] = fiveMin['Date'] - pd.Timedelta(fiveMin['Date'], unit='s')

删除秒,但是我收到错误:

Value must be Timedelta, string, integer, float, timedelta or convertible

【问题讨论】:

    标签: python python-3.x pandas datetime


    【解决方案1】:

    如果 dtype 已经是 datetime,您可以使用 dt 访问器只返回分钟属性:

    In [43]:
    df['Date'].dt.minute
    
    Out[43]:
    0    33
    1    32
    2    42
    3    41
    Name: Date, dtype: int64
    

    如果需要使用to_datetime进行转换:

    df['Date'] = pd.to_datetime(df['Date'])`
    

    如果日期是字符串并且格式正确,您可以在 : 上拆分并提取倒数第​​二个拆分:

    In [46]:
    df['Date'].str.split(':').str[-2]
    
    Out[46]:
    0    33
    1    32
    2    42
    3    41
    Name: Date, dtype: object
    

    这会返回一个字符串系列,但是,如果您想要 int,那么您可以使用 astype(int) 强制转换为 int:

    In [47]:
    (df['Date'].str.split(':').str[-2]).astype(int)
    
    Out[47]:
    0    33
    1    32
    2    42
    3    41
    Name: Date, dtype: int32
    

    【讨论】:

      猜你喜欢
      • 2016-07-05
      • 2019-06-16
      • 2020-10-19
      • 2019-06-27
      • 2019-12-07
      • 1970-01-01
      • 1970-01-01
      • 2019-07-11
      相关资源
      最近更新 更多