我有大约5000个文本文件,这些文件的日期存储在yyyy-mm-ddthh:mm:mm:ss.000z的格式中,并希望将此格式更改为mm/dd/yyyyHH:MM AM/PM。
我在知道每个日期格式之前都有字符串Closed:
的优势。
我一直在使用以下内容来更改似乎有效的日期格式:
def datePrettyPrint(date):
d = dateutil.parser.parse(date)
return(d.strftime('%m/%d/%Y %I:%M %p'))
到目前为止,我有以下内容:
import fileinput, os
directory = "/home/ubuntu/workspace/files/"
for filename in os.listdir(directory):
with open(filename, 'r') as file :
filedata = file.read()
filedata = filedata.replace('Closed: FORMAT1', 'Closed: FORMAT2')
with open('file.txt', 'w') as file:
file.write(filedata)
我不知道的是如何服用FORMAT1
并将其更改为FORMAT2
。我希望我在这里附近。
编辑:文件中的文本示例
Subject: Random Text
Author: Some Name
Closed: 2014-11-21T17:39:43.000Z
Here is a message with more text
这是我要找到和替换的第三行。
您可以使用正则表达式。网络上有一些图案库,或者您可以自己编写。Python的部分非常直截了当,沿着:
的线条。import re
import datetime
for match in re.findall(mySearchPattern, textToSearch)
#convert match to new format
datetime_object = datetime.strptime(match, "%Y-%m-%dT%H:%m:%s.000Z")
dateNewFormat = datetime_object.strftime("%m/%d/%Y %H:%M %p")
#substitute the old date with the new
re.sub(match, dateNewFormat, textToSearch)