PythonStrptime 不返回日期,而是返回整个文本文件

Python Strptime not returning a date, but returning entire text file

我正在尝试从文本文件中删除日期,但到目前为止我所做的一切都是 returns 整个文本文件减去换行符和特殊字符。为了检查我的代码,我已将文本文件剥离成一小段。文本文件内容如下:

03/01/2018

L205:

On-site 7:00 AM, no crew on-site

On-site 11:30 AM crew has excavated for the vessel pad and is watering rock for placement and compaction. Excavation is measured out and meets the requirements including overex on the plans. Off-site 12:00 PM.

CBK-54:

On-site 7:10 AM crew is installing RCP, crew has installed approximately 80 feet from the manhole. Slurry arrives and the manhole is slurried in place. Off-site 8:30 AM

On-site 1:10 PM, crew has installed more RCP and is nearing completion. Soil is holding up well. Off-site 1:40 PM

我想从名为 "Daily_Reports.txt" 并存储在我的桌面上的文本文件中删除日期“03/01/2018”。

目前我试过的代码如下:

import datetime

reports = open('C:/Users/onlyn_000/Desktop/Daily_Reports.txt').read()
print(datetime.datetime.strptime(reports, '%m/%d/%Y').date())

我什至不确定这是否是解决我的问题的正确方法。我最终想为每个站点(L205、CBK-54 等)提取每个 sentence/paragraph 以输入到 excel 电子表格,甚至每天单独的文本文件。作为第一步,我只想去掉日期。任何输入将不胜感激。

编辑:

下面mobone给出了这个问题的答案。对我有用的代码如下:

import datetime
import re

reports = open('C:/Users/onlyn_000/Desktop/Daily_Reports.txt').read()
dates = re.findall('[0-9][0-9]\/[0-9][0-9]\/[0-9]*', reports)

for x in dates:
    print(datetime.datetime.strptime(x, '%m/%d/%Y').date())

编辑 2:

供以后reader参考。我还意识到 re.findall returns 列表和我编写的 for 循环仅将日期重新格式化为日期时间格式。我什至不确定我的应用程序是否需要日期时间格式,我可能只能使用该列表。

您必须查看 re.findall('[0-9][0-9]\/[0-9][0-9]\/[0-9]*', reports) 以从文件中提取日期字符串。然后使用 strptime 解析它。