提问人:Saradindu Samanta 提问时间:7/14/2023 最后编辑:Mike 'Pomax' KamermansSaradindu Samanta 更新时间:8/30/2023 访问量:65
字符串的算术运算
Arithmetic operation on string
问:
我有一个字符串.它看起来像:
00:00:08
00:40:20
01:50:20
.....
等等。
在第一行中,00 是小时,接下来的 00 是分钟,08 是秒。我需要获得总秒数。我正在尝试拆分字符串并将第一个元素乘以 3600,将第二个元素乘以 60 并保持第 3 个元素不变。因此,对于第一行,它将是 003600 + 00 60 + 08。但是,当我尝试乘法而不是乘法时,它正在进行迭代。
if ':' in entry:
t = entry
# print(t)
for item in t:
t1,t2,t3 = t.split(":")
print(t1,t2,t3)
hour.append(int(t1))
hour1 = hour*3600
minute.append(int(t2))
minute1 = minute*60
second.append(int(t3))
second1 = second
但这是行不通的。你能给出一些想法吗?
谢谢。
在上一节中进行了介绍。
答:
0赞
Xiaomin Wu
7/14/2023
#1
- 首先,您可以从 origin str 获取时间 str
s = """
00:40:20
01:50:20
"""
ss = [t.strip() for t in s.split("\n") if t.strip() != ""]
print(ss)
哪个输出
['00:40:20', '01:50:20']
- 然后,您可以使用包 datetime 中的 TimeDelta 来获取秒数
from datetime import datetime, timedelta
delta = datetime.strptime(ss[1], "%H:%M:%S") - datetime.strptime(ss[0], "%H:%M:%S")
print(delta.seconds)
你会得到
4200
0赞
Codist
7/14/2023
#2
datetime 模块具有有助于解决此问题的功能。但是,如果您不想使用其中任何一个(例如,strptime),则可以编写自己的自定义函数。
下面是使用自定义函数和日期时间功能来实现相同目标的代码
from collections.abc import Iterator
from datetime import datetime
s = """\
00:40:20
01:50:20
"""
def total_seconds(s: str) -> int:
def _tsg(s: str) -> Iterator:
for n, m in zip(s.split(':'), [3600, 60, 1]):
yield int(n) * m
return sum(_tsg(s))
print('Using custom function')
for line in s.splitlines():
print(line, total_seconds(line))
epoch = datetime(1900, 1, 1)
print('\nUsing datetime module')
for line in s.splitlines():
d = datetime.strptime(line, '%H:%M:%S')
print(line, int((d-epoch).total_seconds()))
输出:
Using custom function
00:40:20 2420
01:50:20 6620
Using datetime module
00:40:20 2420
01:50:20 6620
0赞
user19077881
7/14/2023
#3
如果你想用Basic Python以最简单的方式做到这一点,那么只需在换行符上拆分,然后在冒号上拆分并进行计算:
s = '''
00:40:20
01:50:20
'''
for t in s.strip().split('\n'):
nums = t.split(':')
secs = int(nums[0])*3600 + int(nums[1])*60 + int(nums[2])
print(secs)
给
2420
6620
0赞
cards
7/14/2023
#4
看看内置模块 datetime
,用于解析字符串并获取您需要的时间数量。datetime.strptime
from datetime import datetime
def str2seconds(s):
# parse the string and convert as seconds
dt = datetime.strptime(s, "%H:%M:%S")
return sum(t*60**i for i, t in enumerate((dt.second, dt.minute, dt.hour)))
str_times = """
00:00:08
00:40:20
01:50:20
""".strip('\n')
# apply the conversion to each
print(*map(str2seconds, str_times.splitlines()), sep='\n')
#2420
#6620
0赞
Manuel Marcus
8/30/2023
#5
您需要先将字符串转换为整数。
例如,此代码:将输出“11111”而不是“6”。print("1" * 5)
此代码应有效:
timeString = """
02:11:59
11:34:06
"""
times = timeString.splitlines()
for time in times:
if ":" in time:
timeList = time.split(":")
seconds = 3600 * int(timeList[0]) + 60 * int(timeList[1]) + int(timeList[2])
print(seconds)
评论