我正在尝试在日期时间字符串之后打印内容,就像今天的日期09-04-2019(mm-dd-yy)我想在09042019字符串开始时打印所有内容,在此之前不会打印任何内容。根据string格式化日期。但是无法在该日期substring之后打印。这是我到目前为止所做的:
from datetime import datetime
now = datetime.now() # current date and time
year = now.strftime("%Y")
month = now.strftime("%m")
day = now.strftime("%d")
date_time = now.strftime("%m%d%Y")
d=str(date_time)
print(d)
content='''(1115 09032019) Arafat hello
(1116 09032019) Arafat a
(1116 09032019) Arafat b
(1117 09032019) space w
(1117 09042019) space a
(1117 09042019) space a'''
print(content)
body=content[:content.find(d)]
我希望09042019开始时的输出是这样的
(1117 09042019) space a
(1117 09042019) space a
答案 0 :(得分:0)
我的尝试
from datetime import datetime
now = datetime.now() # current date and time
year = now.strftime("%Y")
month = now.strftime("%m")
day = now.strftime("%d")
date_time = now.strftime("%m%d%Y")
d=str(date_time)
print(d)
content='''(1115 09022019) Arafat hello
(1116 09022019) Arafat a
(1116 09032019) Arafat b
(1117 09032019) space w
(1117 09042019) space a
(1117 09042019) space a'''
print(content)
print('-- result --')
# find d
d_pos = content.find(d)
# find where the line containing d starts
d_pos_fullline = content.rfind('\n', 0, d_pos) + 1
body=content[d_pos_fullline:]
print(body)
答案 1 :(得分:0)
如果我对它的理解正确,那么您要打印所有包含变量d
的行。在这种情况下,下面的代码应该可以执行您想要的操作:
import itertools
content='''(1115 09032019) Arafat hello
(1116 09032019) Arafat a
(1116 09032019) Arafat b
(1117 09032019) space w
(1117 09042019) space a
(1117 09042019) space a'''
d = '09042019' # Hardcoded for testing
# Skip (drop) all the lines until we see 'd'
lines = iter(content.splitlines())
lines = itertools.dropwhile(lambda line: d not in line, lines)
# Print the rest of the lines
for line in lines:
print(line)
itertools.dropwhile
将跳过行,直到它第一次遇到包含变量d
的行。