如何在Python 3的dateutil解析器中解析超过24小时的日期? [英] How do I parse dates with more than 24 hours in dateutil's parser in Python 3?

查看:56
本文介绍了如何在Python 3的dateutil解析器中解析超过24小时的日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在"27:32:18"这样的栏中有很多次,这意味着有人在等待27小时32分钟18秒.每当我尝试解析这些值时,我都会不断收到"ValueError:小时必须在0..23中."

I currently have a bunch of times in a column written like "27:32:18", meaning someone was waiting for 27 hours, 32 minutes, and 18 seconds. I keep getting "ValueError: hour must be in 0..23" whenever I try to parse these values.

我应该如何解析这些值或将它们转换为更标准的格式?我尝试对单个值进行以下测试:

How should I go about parsing those values or converting them to a more standard format? I tried the following as a test on a single value:

time1 = "56:42:12"
time2 = time1.split(':')
time2 = [int(n) for n in time2]
time2.insert(0, time2[0] // 24)
time2[1] %= 24

此时,time2是一个由[2、8、42、12]组成的列表,相当于2天,8小时,42分钟和12秒.我将如何以几天,几小时,几分钟和几秒钟的时间将其转换为Python日期时间表示形式,从而允许Python对其进行解析?请注意,我最终将对这些表示等待时间的时间值进行无监督的聚类.

At that point, time2 is a list consisting of [2, 8, 42, 12], which is equivalent to 2 days, 8 hours, 42 minutes, and 12 seconds. How would I go about converting that to a Python datetime representation in days, hours, minutes, and seconds in a way that will allow Python to parse it? Note that I will eventually be doing unsupervised clustering on these time values, which represent waiting times.

推荐答案

您没有日期,但是有一定的持续时间.这可能与日期和时间戳有关,但是只涉及相同的时间单位,并且显示的方式类似于时间戳.

You don't have a date, you have a time duration. That may be related to dates and timestamps, but only in that the same units of time are involved and are displayed similarly to timestamps.

因此,您不能使用 dateutil 解析此类值.拆分并解析自己很容易:

As such, you cannot use dateutil for parsing such values. It is easy enough to split out and parse yourself:

hours, minutes, seconds = map(int, time1.split(':'))

然后可以使用 datetime.timedelta()对象表示持续时间:

You can then use a datetime.timedelta() object to represent the duration:

td = datetime.timedelta(hours=hours, minutes=minutes, seconds=seconds)

这将以天,秒和微秒为单位跟踪增量:

This'll then track the delta in terms of days, seconds and microseconds:

>>> import datetime
>>> time1 = "56:42:12"
>>> hours, minutes, seconds = map(int, time1.split(':'))
>>> datetime.timedelta(hours=hours, minutes=minutes, seconds=seconds)
datetime.timedelta(2, 31332)

这篇关于如何在Python 3的dateutil解析器中解析超过24小时的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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