請檢查。 評論內嵌代碼。
from datetime import datetime
v = ['4/29/2016 8:25:58 AM', '5/25/2016 2:22:22 PM', 'True', 'Foo', 1]
def fixdate(_params):
print "Before changing format ..."
print _params
#First date in list
tstamp = datetime.strptime(_params[0], "%m/%d/%Y %I:%M:%S %p")
#Add %p after %S if AM or PM is required
newtstamp = datetime.strftime(tstamp, "%m-%d-%Y %I:%M:%S")
#Update the element in list
_params[0] = newtstamp
#Second date in list
tstamp = datetime.strptime(_params[1], "%m/%d/%Y %I:%M:%S %p")
newtstamp = datetime.strftime(tstamp, "%m-%d-%Y %I:%M:%S")
#Update the element in list
_params[1] = newtstamp
print "After changing format..."
print _params
fixdate(v)
輸出:
C:\Users\dinesh_pundkar\Desktop>python c.py
Before changing format ...
['4/29/2016 8:25:58 AM', '5/25/2016 2:22:22 PM', 'True', 'Foo', 1]
After changing format...
['04-29-2016 08:25:58', '05-25-2016 02:22:22', 'True', 'Foo', 1]
C:\Users\dinesh_pundkar\Desktop>
代碼列表理解:
from datetime import datetime
v = ['4/29/2016 8:25:58 AM', '5/25/2016 2:22:22 PM', 'True', 'Foo', 1]
def fixdate(_params):
print "Before changing format ..."
print _params
_params = [i if ':' not in str(i) and '/' not in str(i) else datetime.strftime(datetime.strptime(i, "%m/%d/%Y %I:%M:%S %p"), "%m-%d-%Y %I:%M:%S") for i in _params]
print "After changing format..."
print _params
fixdate(v)
輸出:
C:\Users\dinesh_pundkar\Desktop>python c.py
Before changing format ...
['4/29/2016 8:25:58 AM', '5/25/2016 2:22:22 PM', 'True', 'Foo', 1]
After changing format...
['04-29-2016 08:25:58', '05-25-2016 02:22:22', 'True', 'Foo', 1]
C:\Users\dinesh_pundkar\Desktop>
@dobbs - 請讓我知道,如果你想任何其他信息。 –
感謝您的提交。我正在使用的實際列表要多得多(17個元素),並且如果可能,我希望通過列表理解來完成此操作,而不是指定每個需要修改的索引。我更新了上述問題以解決此問題 – dobbs
@dobbs - 請檢查更新後的答案。 –