使用Python格式化文件中的日期字符串

时间:2016-08-31 12:49:57

标签: python datetime

我从我的客户端获取包含可变数量列的csv文件。在这些列中,可能有一些列包含日期字符串,但未定义顺序,例如:

column1str|column2dt|column3str|column4int|column5int|column6dt
ab c1|10/20/2010|1234|10.02|530.55|30-01-2011
ab c2|10/10/2010|12346|11.03|531|05-05-2012
abc3|10/10/2010|122|12|532.44|11-09-2008
abc4|10/11/2010|110|13|533|01-11-2013
abc5|10/10/2010|11111|14|534|30-02-2012

我从客户端获取日期字符串的格式作为输入,在上面的输入中有两种格式的日期字符串MM/dd/yyyydd-MM-yyyy

我想在文件本身中转换特定格式dd-MM-yyyyTHH:mmZ的所有日期。我知道在给出输入日期格式时如何将日期字符串转换为所需的日期字符串。我在这里面临的挑战是如何替换文件中特定列的日期字符串。

2 个答案:

答案 0 :(得分:2)

试试这个:

import pandas as pd
data=pd.read_csv('so.txt',delimiter='|',parse_dates=['column2dt','column6dt'])

答案 1 :(得分:1)

首先,请阅读Python datetime.strptime()格式字符串的参考: https://docs.python.org/3.5/library/datetime.html#strftime-strptime-behavior

用于CSV解析:https://docs.python.org/3.5/library/csv.html

我的回答只会使用标准的Python。作为一种有效的替代方案,您可以使用专门的数据分析库,例如已经建议的pandas。

MM/dd/yyyy格式为%m/%d/%Y格式(实际上是C标准格式),dd-MM-yyyy%d-%m-%Y

现在我不确定您是否希望日期被您的python脚本“自动发现”,或者您希望能够手动指定适当的列和格式。所以我会为两者建议一个脚本:

这将转换INPUT_DATE_FORMATS地图中指定的列名称和输入格式中的所有日期:

from datetime import datetime

import csv

# file that will be read as input
INPUT_FILENAME = 'yourfile.csv'
# file that will be produced as output (with properly formatted dates)
OUTPUT_FILENAME = 'newfile.csv'


INPUT_DATE_FORMATS = {'column2dt': '%m/%d/%Y', 'column6dt': '%d-%m-%Y'}

OUTPUT_DATE_FORMAT = '%d-%m-%YT%H:%MZ'

with open(INPUT_FILENAME, 'rt') as finput:
    reader = csv.DictReader(finput, delimiter='|')
    with open(OUTPUT_FILENAME, 'wt') as foutput:
        writer = csv.DictWriter(foutput, fieldnames=reader.fieldnames, delimiter='|') # you can change delimiter if you want
        for row in reader: # read each entry one by one
            for header, value in row.items(): # read each field one by one
                date_format = INPUT_DATE_FORMATS.get(header)
                if date_format:
                    parsed_date = datetime.strptime(value, date_format)
                    row[header] = parsed_date.strftime(OUTPUT_DATE_FORMAT)
            writer.writerow(row)

这将尝试使用INPUT_DATE_FORMATS中指定的所有格式解析输入文件中的每个字段,并编写一个新文件,其中包含使用OUTPUT_DATE_FORMAT格式化的所有日期:

from datetime import datetime

import csv

# file that will be read as input
INPUT_FILENAME = 'yourfile.csv'
# file that will be produced as output (with properly formatted dates)
OUTPUT_FILENAME = 'newfile.csv'


INPUT_DATE_FORMATS = ('%m/%d/%Y', '%d-%m-%Y')
OUTPUT_DATE_FORMAT = '%d-%m-%YT%H:%MZ'

with open(INPUT_FILENAME, 'rt') as finput:
    reader = csv.DictReader(finput, delimiter='|')
    with open(OUTPUT_FILENAME, 'wt') as foutput:
        writer = csv.DictWriter(foutput, fieldnames=reader.fieldnames, delimiter='|') # you can change delimiter if you want
        for row in reader: # read each entry one by one
            for header, value in row.items(): # read each field one by one
                for date_format in INPUT_DATE_FORMATS: # try to parse a date
                    try:
                        parsed_date = datetime.strptime(value, date_format)
                        row[header] = parsed_date.strftime(OUTPUT_DATE_FORMAT)
                    except ValueError:
                        pass
            writer.writerow(row)