【问题标题】:Does anyone know how to get the time to format correctly when the Hour/Minute/Second is a SINGLE digit in python or pandas当 Hour/Minute/Second 是 python 或 pandas 中的单个数字时,有谁知道如何正确格式化时间
【发布时间】:2021-08-01 14:08:32
【问题描述】:

我的数据框中的某些行的时间为“13:2:7”,我希望它们为“13:02:07”。

我已尝试将 pd.to_datetime 应用于列,但它不起作用

有人可以建议一些方法以标准格式格式化时间

【问题讨论】:

  • 你可以试试strftime。在打印到日期时间列之前应用 if。它将从日期时间对象生成任何所需格式的字符串。
  • 是的,谢谢您的提及。也可以使用strftime

标签: python pandas datetime time formatting


【解决方案1】:

找到解决办法

我通过pandas解决了to_timedelta

pd.to_timedelta("13:2:3") 或通过它传递数据框的列

结果:

“13:02:03”

ps:你会得到“0 days 13:02:03”的结果

为了去掉0天

df["column_name"].astype(str).map(lambda x: x[7:]))

我们将分割最初的 0 天字符串

注意:最终结果将是表单字符串

如果你想要时间对象,

使用来自datetime 模块的pandas pd.to_datetimestrftime

【讨论】:

  • 使用此代码,当小时数从 0 开始时(如 07:15:15),您将得到意想不到的结果。它也会去掉前导零。 lstrip 参数用作字符集,因此当它们中的任何一个出现在字符串的左端时 - 它将被剥离。
  • 是的,我意识到了,谢谢指出。我已经使用切片操作来删除天数部分
猜你喜欢
  • 2013-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-29
  • 1970-01-01
  • 1970-01-01
  • 2015-02-10
  • 2018-03-07
相关资源
最近更新 更多