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
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)
无需使用任何花招,只需使用
str.split()
作为:可能不是最干净的方法,但您可以尝试以下方法:
结果是:
^{pr2}$对来自
datetime
模块的strptime
和strftime
函数使用以下方法:输出(对于示例性线路):
^{pr2}$https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior
相关问题 更多 >
编程相关推荐