gpt4 book ai didi

python - 值错误: time data '67:01' does not match format '%M:%S'

转载 作者:行者123 更新时间:2023-11-30 23:06:26 24 4
gpt4 key购买 nike

我有一个 pandas 数据框,其中有一个名为“Used”的文本列,其中包含电话通话的持续时间(以分钟为单位:秒)。我想将其转换为持续时间格式。问题是某些分钟大于 59,因此会出现错误:

time data '67:01' does not match format '%M:%S'

转换的代码是:

df.Used.apply(lambda x: datetime.datetime.strptime(x, '%M:%S'))

有没有一种简单的方法可以将其转换为十进制分钟格式?类似 67.01666 代表 67:01?

最佳答案

基于 datetime 的文档 对象,您只能在 [0-60) 范围内获取分钟值:

The year, month and day arguments are required. tzinfo may be None, or an instance of a tzinfo subclass. The remaining arguments may be ints or longs, in the following ranges:

  1. 0 <= hour < 24
  2. 0 <= minute < 60
  3. 0 <= second < 60
  4. 0 <= microsecond < 1000000

因此,没有办法消除该错误。如果您想将其转换为十进制分钟格式(我猜这只是一个十进制),您需要像这样手动执行此操作:

# Split the string, join it and cast it to float
df.Used.apply(lambda x : float(".".join(x.split(":"))))

哪些输出:

In [5]: df = pd.DataFrame([['87:01'],['911:11']],columns=['Used'])

In [6]: df.Used.apply(lambda x : float(".".join(x.split(":"))))
Out[6]:
0 87.01
1 911.11
Name: Used, dtype: float64

关于python - 值错误: time data '67:01' does not match format '%M:%S' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32667006/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com