如何使用python更改分隔文件中的日期格式?

时间:2016-10-26 12:09:39

标签: python date delimited-text

我有一个管道分隔的文本文件,其中包含以下记录:

angular2

寻找将ABC|1234|10/26/2016|PQRS|02/27/2016| GHI|4321|02/27/2016|UOIP|10/26/2016| 格式更改为mm/dd/yyyy

的方法

4 个答案:

答案 0 :(得分:1)

strptime模块中的strftimedatetime函数使用以下方法:

import datetime

# while iterating through the lines with a given format
# ...
line = 'ABC|1234|10/26/2016|PQRS|02/27/2016|'

line = '|'.join([item if k not in [2,4] else datetime.datetime.strptime(item, '%m/%d/%Y').strftime("%Y-%m-%d")
        for k, item in enumerate(line.split('|'))])

print(line)

输出(示例性行):

ABC|1234|2016-10-26|PQRS|2016-02-27|

https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior

答案 1 :(得分:0)

不使用任何奇特的技巧,只需使用str.split() as:

即可实现
>>> my_string = "ABC|1234|10/26/2016|PQRS|02/27/2016|"
>>> mm, dd, yy = my_string.split("|")[2].split("/")
>>> print "{}-{}-{}".format(yy, mm, dd)
2016-10-26

答案 2 :(得分:0)

您还可以进行正则表达式替换:

import re

string = """ABC|1234|10/26/2016|PQRS|02/27/2016|

GHI|4321|02/27/2016|UOIP|10/26/2016|"""

dates = re.sub('(\d{1,2})/(\d{1,2})/(\d{4})', '\g<3>/\g<1>/\g<2>', string)

print dates

答案 3 :(得分:0)

可能不是最干净的方法,但您可以尝试以下方法:

my_string = "ABC|1234|10/26/2016|PQRS|02/27/2016|"

#Split the string with the '|' character and return a list.
string_elements=my_string.split('|')

#The item 2 of the list (which is the first date) is split according to the '/' character
string_elements[2]=string_elements[2].split('/')
#The item 2 is transformed by making a rotation of the element to have the format yyyy-mm-dd and is joined on the character '-'    
string_elements[2]='-'.join(string_elements[2][-1:] + string_elements[2][:-1])

#Same as above for teh item 4 which is the second date
string_elements[4]=string_elements[4].split('/')
string_elements[4]='-'.join(string_elements[4][-1:] + string_elements[4][:-1])

#The list of item is joined with the '|' character to reform a string
my_transformed_string='|'.join(string_elements)
print my_transformed_string

结果是:

ABC|1234|2016-10-26|PQRS|2016-02-27|