python - 是否可以通过将文本存储为一个字符串或使用 Python 的其他内容来添加或减去文本中的所有时间?

标签 python datetime time

我的问题与 YouTube 描述中列出的时间有关。如果我想从这个轨道描述的前面去除 5 秒的死气(在从视频中去除 5 秒之后),我需要一个函数来发现和改变所有时间 -5 秒而不是自己做数学运算。我想将其粘贴到脚本中并复制终端的输出以粘贴到 YouTube 中...
我可以将它存储为这样的变量并对它做些什么吗?

times = ("""
Published on Aug 24, 2012
Band: Metallica
Album: Master of Puppets
Released: March 3, 1986
Genre: Thrash Metal

Tracks:
0:00 Battery
5:11 Master Of Puppets
13:46 Welcome Home (Sanitarium)
20:14 The Thing That Should Not Be
26:49 Disposable Heroes
35:04 Leper Messiah
40:46 Orion
49:11 Damage, Inc.
Heres a link for the lyrics
http://www.darklyrics.com/lyrics/metallica/masterofpuppets.html#1All 
Rights to Metallica!
I do not own any rights!
""")

我尝试了一些方法,但它们最终都涉及大量删除、重写、复制、重新格式化、分离等,但没有看到任何只能对这个字符串进行我想要的更改的东西一次通行证。我尝试解决的问题过于复杂且无用,无法在此处发布。我最终放弃了,一直用计算器手动更改(在比这个例子更复杂的视频上)。

最佳答案

试试这个:

import re, datetime
p = '\d+:\d+'
for i in re.finditer(p, times):
    m, s = i.group().split(':')
    if m != '0' and s != '00':
        time2 = datetime.datetime(* [1] * 4, int(m), int(s)) - datetime.timedelta(seconds=5)
        newtime = ':'.join([str(time2.minute), str(time2.second).zfill(2)])
        print(newtime)
        times = times[:i.start()] + newtime + times[i.end():]
print(times)

2017, 5, 5, 5 只是 holder 值——如果有人知道更好的方法,请在评论中说出来。

附评论:

import re, datetime # import modules
p = '\d+:\d+' # this is a regular expression to match digits, followed by a colon, then more digits (the format all of the times are in)
for i in re.finditer(p, times): # iterate through all of the matches found
    m, s = i.group().split(':') # split time by ':' -- this puts the first number, the minutes, into the m variable, and the seconds into the s variable
    if m != '0' and s != '00': # don't subtract at time="0:00"
        time2 = datetime.datetime(* [1] * 4, int(m), int(s)) # make a datetime to match the time of the video. The important parts are the `int(m), int(s)` to represent the minutes and seconds; the other numbers are just filler and can be changed (but not deleted)
        time2 -= datetime.timedelta(seconds=5) # subtract the five seconds
        newtime = ':'.join([str(time2.minute), str(time2.second).zfill(2)]) # put the time back into string format (zfill pads it with 0s to make it two digits)
        print(newtime)
        times = times[:i.start()] + newtime + times[i.end():] # replace the part of time with the new time. since strings are immutable we need to do this weird technique
print(times)

关于python - 是否可以通过将文本存储为一个字符串或使用 Python 的其他内容来添加或减去文本中的所有时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43591572/

相关文章:

python - 拆分字符串而不丢失分隔符(及其计数)

Python:扫雷的floodfill算法

windows - 如何将 UTC 日期时间转换为指定时区?

objective-c - 如何比较时间

java - 转换 XX :XX AM/PM to 24 Hour Clock

python - 如何从 LineString 未排序列表创建多边形

python - 在 python 项目中处理日期和时区

python - 如何在 Python 中将 N 毫秒添加到日期时间

c++ - std::chrono 重复调用 QueryPerformanceFrequency?

python - 什么是 Python 等价于或等于表达式,以获得 return foo 或 foo = 'bar' 工作?