【问题标题】:Remove the time from datetime.datetime in pandas column从 pandas 列中的 datetime.datetime 中删除时间
【发布时间】:2018-07-11 22:30:57
【问题描述】:

我有一个名为 'date' 的 pandas 专栏 它的值和类型类似于2014-07-30 00:00:00 <class 'datetime.datetime'>。 我想从日期中删除时间。最终结果是 datetime.datetime 格式的“2014-07-30”。

我尝试了很多解决方案,比如-

df['PSG Date '] = df['PSG Date '].dt.date

但它给了我错误-

AttributeError: Can only use .dt accessor with datetimelike values

【问题讨论】:

    标签: python pandas datetime


    【解决方案1】:

    我相信首先需要to_datetime,对于dates,请使用dt.date

    df['PSG Date '] = pd.to_datetime(df['PSG Date '], errors='coerce').dt.date
    

    如果想要没有时间的日期时间,请使用dt.floor

    df['PSG Date '] = pd.to_datetime(df['PSG Date '], errors='coerce').dt.floor('d')
    

    【讨论】:

    • 什么是错误? AttributeError: Can only use .dt accessor with datetimelike values ?
    • 现在没有错误但答案即将到来 2014-07-30 00:00:00
    • 时间没有去掉只是类型从datetime.datetime变成了pandas._libs.tslibs.timestamps.Timestamp
    • @ubuntu_noob - to_datetime 的输出除外,如果使用df['PSG Date '] = pd.to_datetime(df['PSG Date ']).dt.date 它仍然不起作用?
    • pd.to_datetime(df['PSG Date ']).dt.date 给出错误 TypeError: invalid string coercion to datetime
    【解决方案2】:

    首先,您应该从datetime 系列开始;如果您没有,请使用pd.to_datetime 强制进行此转换。这将允许矢量化计算:

    df = pd.DataFrame({'col': ['2014-07-30 12:19:22', '2014-07-30 05:52:05',
                               '2014-07-30 20:15:00']})
    
    df['col'] = pd.to_datetime(df['col'])
    

    接下来,请注意您无法从 Pandas 中的 datetime 系列中删除时间。根据定义,datetime 系列将包括“日期”和“时间”组件。

    标准化时间

    您可以使用pd.Series.dt.floorpd.Series.dt.normalize 将时间组件重置为00:00:00

    df['col_floored'] = df['col'].dt.floor('d')
    df['col_normalized'] = df['col'].dt.normalize()
    
    print(df['col_floored'].iloc[0])     # 2014-07-30 00:00:00
    print(df['col_normalized'].iloc[0])  # 2014-07-30 00:00:00
    

    转换为 datetime.date 指针

    您可以将您的 datetime 系列转换为 object 系列,由代表日期的 datetime.date 对象组成:

    df['col_date'] = df['col'].dt.date
    print(df['col_date'].iloc[0])        # 2014-07-30
    

    由于这些不保存在连续的内存块中,df['col_date'] 上的操作将不会被矢量化。

    如何检查差异

    检查dtype 对我们派生的系列很有用。请注意“删除”时间的一个选项涉及将您的系列转换为object

    计算将不使用此类序列进行向量化,因为它由指向 datetime.date 对象的指针组成,而不是连续内存块中的数据。

    print(df.dtypes)
    
    col               datetime64[ns]
    col_date                  object
    col_floored       datetime64[ns]
    col_normalized    datetime64[ns]
    

    【讨论】:

      【解决方案3】:

      您可以通过调用对象的.date() 方法将datetime.datetime 转换为date time.date。例如

       current_datetime = datetime.datetime.now()
       date_only = current_datetime.date()
      

      【讨论】:

      • 我有一个 pandas 专栏...如何对其进行更改?
      猜你喜欢
      • 2021-01-28
      • 1970-01-01
      • 2014-09-07
      • 1970-01-01
      • 1970-01-01
      • 2018-05-01
      • 2020-02-10
      相关资源
      最近更新 更多