Skip to main content
 首页 » 编程设计

python之如何检测和编辑文件中的日期

2024年10月01日6over140

我有一个文件,其中包含一堆包含日期的行,例如:

1, '01-JAN-10', '04-JAN-10', 100, 'HELEN', 'PRICE' 
2, 'MARK', 'TYER', '05-JAN-10', '06-JAN-10', 120 

我想将行的日期部分更改为不同的格式,但我不知道如何检测行的哪一部分有日期字段,也不知道如何用新日期替换它们格式。我已经有一个名为 changeDate(date) 的函数,它在给定错误格式日期的情况下返回格式正确的日期。到目前为止,这是我的代码:

def editFile(filename) 
    f = open(filename) 
 
    while line: 
        line = f.readline() 
        for word in line.split(): 
            #detect if it is a date, and change to new format 
    f.close() 

请您参考如下方法:

您可以使用 strptime 和 try/catch 来执行此操作:

strptime

Return a datetime corresponding to date_string, parsed according to format.

查看来自 strftime() and strptime() Behavior 的更多详细信息.

from datetime import datetime 
 
s="1, '01-JAN-10', '04-FEB-28', 100, 'HELEN', 'PRICE'" 
for word in s.replace(' ','').replace('\'','').split(','): 
    try: 
        dt=datetime.strptime(word,'%y-%b-%d') 
        print('{0}/{1}/{2}'.format(dt.month, dt.day, dt.year)) 
    except Exception as e: 
        print(word) 

结果:

1 
1/10/2001 
2/28/2004 
100 
HELEN 
PRICE