【问题标题】:python 3 pandas convert string time into yyyy-mm-ddpython 3 pandas将字符串时间转换为yyyy-mm-dd
【发布时间】:2020-01-11 22:16:30
【问题描述】:

假设我在名为 df 的数据帧中有以下时间戳

           time
1          2019-05-03 15:26:37.000
2          2019-05-10 19:26:29.000
3          2019-05-10 23:39:07.000
4          2019-05-08 13:52:08.000

我打算把它转换成

           time
1          2019-05-03
2          2019-05-10
3          2019-05-10
4          2019-05-08

这样我就可以分组计算每天有多少个日期点

df2=pd.to_datetime(df['time'], format='%d-%b-%y')

返回以下错误

ValueError: time data '2019-05-04 14:08:33.000' does not match format '%d-%b-%y' (match)

TypeError: Unrecognized value type: <class 'str'>

During handling of the above exception, another exception occurred:

如果我这样做:

request_time_date_df2=pd.to_datetime(ride_df['requested_time'], unit='D')

返回

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
pandas/_libs/tslib.pyx in pandas._libs.tslib.array_with_unit_to_datetime()

ValueError: could not convert string to float: '2019-05-04 14:08:33.000'

如果我这样做

df2=pd.to_datetime(df['time'], format='%d-%b-%y', errors='ignore')

返回相同的

           time
1          2019-05-03 15:26:37.000
2          2019-05-10 19:26:29.000
3          2019-05-10 23:39:07.000
4          2019-05-08 13:52:08.000

有什么想法吗?谢谢!

【问题讨论】:

    标签: python-3.x pandas datetime


    【解决方案1】:

    其他可能的解决方案:

    df = pd.DataFrame({'time':['2019-05-03 15:26:37.000', '2019-05-10 19:26:29.000', '2019-05-10 23:39:07.000', '2019-05-08 13:52:08.000']})
    
    df['time'] = pd.to_datetime(df['time']).dt.strftime('%Y-%m-%d')
    
    print(df)
    

    打印:

             time
    0  2019-05-03
    1  2019-05-10
    2  2019-05-10
    3  2019-05-08
    

    注意:如果要按天分组,则无需提前格式化天,只需将其转换为日期时间并查看pandas.Grouper(频率设置为'D')。

    例如:

    df = pd.DataFrame({'time':['2019-05-03 15:26:37.000', '2019-05-10 19:26:29.000', '2019-05-10 23:39:07.000', '2019-05-08 13:52:08.000'],
                       'data':[1, 1, 1, 1]})
    
    df['time'] = pd.to_datetime(df['time'])
    
    print(df.groupby(pd.Grouper(key='time', freq='D'))['data'].sum())
    

    打印:

    time
    2019-05-03    1
    2019-05-04    0
    2019-05-05    0
    2019-05-06    0
    2019-05-07    0
    2019-05-08    1
    2019-05-09    0
    2019-05-10    2
    Freq: D, Name: data, dtype: int64
    

    【讨论】:

    • 谢谢!两种解决方案都很好用!学到很多!
    【解决方案2】:

    IIUC,你可以使用:

    pd.to_datetime(df['time']).dt.normalize() # if series is a object dtype
    

    或者:

    df['time'].dt.normalize() #if series is a datetime dtype
    

    1   2019-05-03
    2   2019-05-10
    3   2019-05-10
    4   2019-05-08
    Name: time, dtype: datetime64[ns]
    

    【讨论】:

    • 谢谢!两种解决方案都很好用!学到很多!
    猜你喜欢
    • 1970-01-01
    • 2023-03-15
    • 2012-04-10
    • 2013-06-30
    • 2018-05-19
    • 2019-01-26
    • 2014-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多