ValueError:时间数据"10/11/2006 24:00"与格式“%d/%m/%Y%H:%M"不匹配 [英] ValueError: time data '10/11/2006 24:00' does not match format '%d/%m/%Y %H:%M'

查看:38
本文介绍了ValueError:时间数据"10/11/2006 24:00"与格式“%d/%m/%Y%H:%M"不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试过:

df["datetime_obj"] = df["datetime"].apply(lambda dt: datetime.strptime(dt, "%d/%m/%Y %H:%M"))

但出现此错误:

ValueError:时间数据"2006年10月11日24:00"与格式不匹配'%d/%m/%Y%H:%M'

ValueError: time data '10/11/2006 24:00' does not match format '%d/%m/%Y %H:%M'

如何正确解决?

推荐答案

之所以不起作用,是因为%H 参数仅接受 00 23 (包括两者).因此,这意味着 24:00 是-如错误所说-不是有效的时间字符串.

The reason why this does not work is because the %H parameter only accepts values in the range of 00 to 23 (both inclusive). This thus means that 24:00 is - like the error says - not a valid time string.

因此,我认为除了将字符串转换为有效格式外,我们没有其他选择.为此,我们可以先将 24:00 替换为 00:00 ,然后再为这些时间戳增加日期.

I think therefore we have not much other options than convert the string to a valid format. We can do this by first replacing 24:00 with 00:00, and then later increment the day for these timestamps.

赞:

from datetime import timedelta
import pandas as pd

df['datetime_zero'] = df['datetime'].str.replace('24:00', '0:00')
df['datetime_er'] = pd.to_datetime(df['datetime_zero'], format='%d/%m/%Y %H:%M')
selrow = df['datetime'].str.contains('24:00')
df['datetime_obj'] = df['datetime_er'] + selrow * timedelta(days=1)

因此,最后一行将一天添加到包含 24:00 的行中,以便将 '10/11/2006 24:00'转换为"11/11/2006 24:00" .但是请注意,以上内容是不安全,因为根据时间戳的格式,此操作将/将不起作用.对于上述情况,它将(可能)有效,因为只有一个冒号.但是,例如,如果 datetime 也有秒,则过滤器可能会触发 00:24:00 ,因此可能需要一些额外的工作才能使其工作.

The last line thus adds one day to the rows that contain 24:00, such that '10/11/2006 24:00' gets converted to '11/11/2006 24:00'. Note however that the above is rather unsafe since depending on the format of the timestamp this will/will not work. For the above it will (probably) work, since there is only one colon. But if for example the datetimes have seconds as well, the filter could get triggered for 00:24:00, so it might require some extra work to get it working.

这篇关于ValueError:时间数据"10/11/2006 24:00"与格式“%d/%m/%Y%H:%M"不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆