问题描述
限时送ChatGPT账号..假设您有这种格式的时间:
a = [..., 800.0, 830.0, 900.0, 930.0, 1000.0, 1030.0, ...]
问题是缺少几个小时的前导零.例如00:30
用30
表示,08:00
用800.
和表示00:00
表示为 2400
.是否可以使用 strptime
方法将此数据解析为 time
对象?我尝试使用以下代码
hours = [time.strptime(str(int(i)), "%H%M") for i in a]
但是得到了
ValueError:未转换的数据仍然存在:0
附言我使用的是 Python 2.7.
解决方案使用 zfill
根据需要重新添加那些零:
hours = [time.strptime(i[:-1].zfill(4), "%H%M") for i in a]
通过使用 i[:-1]
我们删除了那个讨厌的尾随点,并且 .zfill(4)
将添加足够的 0
字符向左移动到 4 位数字.
演示:
<预><代码>>>>导入时间>>>a = ['800.', '830.', '900.', '30.']>>>[time.strptime(i[:-1].zfill(4), "%H%M") for i in a][time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=8, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=1, tm_isdst=-1), time.struct_time=1(tm0_year), tm_mon=1, tm_mday=1, tm_hour=8, tm_min=30, tm_sec=0, tm_wday=0, tm_yday=1, tm_isdst=-1), time.struct_time(tm_year=1900, tm_mon=1), tm_hour=9, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=1, tm_isdst=-1), time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour_min=0,=3, tm_sec=0, tm_wday=0, tm_yday=1, tm_isdst=-1)]如果它们是浮点值,请使用 format()
函数 为您提供零填充值:
这样做:
hours = [time.strptime(format(i % 2400, '04.0f'), "%H%M") for i in a]
其中 % 2400
将您的值标准化为 0. 到 2399. 范围.
Suppose you have time in this format:
a = [..., 800.0, 830.0, 900.0, 930.0, 1000.0, 1030.0, ...]
The problem is that leading zeroes for hours are missing. For example 00:30
is represented by 30
, 08:00
is represented by 800.
and 00:00
is represented by 2400
.
Is it possible to parse this data to time
object using strptime
method?
I tried using following code
hours = [time.strptime(str(int(i)), "%H%M") for i in a]
but got
ValueError: unconverted data remains: 0
P.S. I'm using Python 2.7.
解决方案Use zfill
to add those zeros back as needed:
hours = [time.strptime(i[:-1].zfill(4), "%H%M") for i in a]
By using i[:-1]
we remove that pesky trailing dot, and .zfill(4)
will add enough 0
characters to the left to make it to 4 digits.
Demo:
>>> import time
>>> a = ['800.', '830.', '900.', '30.']
>>> [time.strptime(i[:-1].zfill(4), "%H%M") for i in a]
[time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=8, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=1, tm_isdst=-1), time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=8, tm_min=30, tm_sec=0, tm_wday=0, tm_yday=1, tm_isdst=-1), time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=9, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=1, tm_isdst=-1), time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=30, tm_sec=0, tm_wday=0, tm_yday=1, tm_isdst=-1)]
If they are float values instead, use the format()
function on them to give you zero-padded values:
>>> format(800., '04.0f')
'0800'
So do this:
hours = [time.strptime(format(i % 2400, '04.0f'), "%H%M") for i in a]
where % 2400
normalizes your values to the 0. to 2399. range.
这篇关于在 Python 中通过 strptime 解析没有前导零的小时数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论