【问题标题】:Pandas to_datetime not following format & producing incorrect results熊猫 to_datetime 不遵循格式并产生不正确的结果
【发布时间】:2022-01-14 19:02:52
【问题描述】:

我有一个包含两列时间的数据框(BgnDateEndDate)。目前这些列的格式是float64,但我需要它们的熊猫日期时间格式。我尝试以%Y-%m-%d 的格式运行pd.to_datetime,但我总是得到秒数,这是我不想要的。此外,Pandas 计算的列值不正确。下面是我的输入、脚本和输出的示例:

BgnDate = 19700907

input_data_df[['BgnDate', 'EndDate']] = input_data_df[['BgnDate', 'EndDate']].apply(lambda x: pd.to_datetime(x,format='%Y-%m-%d', errors='coerce'))

BgnDate = 1970-01-01 00:00:00.019990907

我希望我的输出看起来像:'1999-09-07'

^^ 请注意,输出的月份和日期不正确。

知道我哪里出错了吗?

【问题讨论】:

  • 日期应该是多少? 1970-09-07?
  • 是的,格式为'yyyy-mm-dd'

标签: python pandas datetime lambda format


【解决方案1】:

我认为您的格式不正确。试试%Y%m%d 而不是%Y-%m-%d

df[['BgnDate', 'EndDate']] = df[['BgnDate', 'EndDate']].apply(lambda x: pd.to_datetime(x,format='%Y%m%d', errors='coerce'))

【讨论】:

  • 但我想用破折号分隔每个测量值。我相信我以前做过,没有问题。
  • 那么BgnDate = 19700907 应该评估什么?
  • 我想要的格式是:'1979-09-07'
  • 你试过我的代码了吗?它会为你做到这一点。
  • 成功了!谢谢你。猜猜这只是一个很小的格式问题:') 非常感谢
猜你喜欢
  • 1970-01-01
  • 2016-07-08
  • 1970-01-01
  • 2018-06-05
  • 1970-01-01
  • 2020-08-14
  • 1970-01-01
  • 2021-05-22
  • 1970-01-01
相关资源
最近更新 更多