【问题标题】:convert to datetime and format date in pandas in a single oneliner在单个 oneliner 中转换为 pandas 中的日期时间和格式日期
【发布时间】:2023-03-10 01:56:01
【问题描述】:

我有一个数据框,其中两列包含非格式化日期。

这些列中的数据如下: 2011-06-10T00:00:00.000+02:00

我想只获取日期并对其进行格式化。

在 Jupyter 笔记本中,我执行以下操作:

sections['produced'] = pd.to_datetime(sections['produced'])
sections['produced'] = [d.strftime('%Y-%m-%d') if not pd.isnull(d) else '' for d in sections['produced']]

sections['updated'] = pd.to_datetime(sections['updated'])
sections['updated'] = [d.strftime('%Y-%m-%d') if not pd.isnull(d) else '' for d in sections['updated']]

sections.info()     

然后我打印出部分数据框,并且确实正确打印了日期。

但是:

sections.info()

仍然告诉我这些列是非空对象而不是日期时间。 为什么?

其次,我的方法似乎在后台不起作用,即日期类型实际上不是日期。 我该怎么办? 最后,代码对于应该是一个衬里的东西来说是超级冗长的,或者不是? (即 pandas 很强大,但也有他的局限性)

编辑 1:回答一些贡献者。我期待日期时间。只是 2008-02-02 只是这一天。 所以在做的时候:

sections['updated'] = pd.to_datetime(sections['updated'])

日期类型被转换。 但是接下来做的时候:

sections['produced'] = [d.strftime('%Y-%m-%d') if not pd.isnull(d) else '' for d in sections['produced']]

所以这里的目的是 a) 转换为日期时间格式 b) 获取日期格式 2008-01-02,我不关心秒 c) 它必须像这样在 jupyter notebook 中打印出来,即日期

【问题讨论】:

  • 你期望什么 dtypes? sections.info() 打印什么? “非格式化”是什么意思? 2011-06-10T00:00:00.000+02:00 是相当标准的 ISO 8601...
  • 一旦'' 与列中的其他数据类型混合,dtype 始终是对象。
  • @QuangHoang 看起来 OP 想要格式化为字符串,所以它无论如何都是对象
  • 我希望我现在澄清
  • 好的,如果你想要 datetime dtype,只需使用pd.to_datetime(column_name)。如果您希望字符串格式为 yyyy-mm-dd,请使用 pd.to_datetime(column_name).dt.strftime('%Y-%m-%d')。请注意,您无法更改 pandas 显示 日期时间值的方式,但只要您 处理 数据,您就不必担心。要获得“人类可读”的输出,请按照所述格式化为字符串。

标签: python pandas datetime format


【解决方案1】:

这应该作为一个班轮工作:

df[['produced','updated']] = df[['produced','updated']].apply(lambda x: pd.to_datetime(x,errors='coerce'))

【讨论】:

  • 这适用于数据类型,现在 ['produced','updated'] 是日期类型,但是在 jupyter notebook 中打印时我仍然看到:2011-04-18 00:00:00+两栏下的 02:00。传递 format='%Y-%m-%d' 似乎不起作用。
【解决方案2】:

只需在to_datetime() 方法中传递errors 参数并将其设置为等于'coerce':-

sections['produced'] = pd.to_datetime(sections['produced'],errors='coerce')
sections['updated'] = pd.to_datetime(sections['updated'],errors='coerce')

【讨论】:

    猜你喜欢
    • 2022-01-09
    • 2015-10-25
    • 1970-01-01
    • 1970-01-01
    • 2016-11-26
    • 1970-01-01
    • 2016-01-27
    • 1970-01-01
    相关资源
    最近更新 更多