这是个涉及到字符串操作的问题,例如
unique_dates = ["January 12,1988","February 11,1995","December 2,1992"]
我想把 "一月 "改为1,"二月 "改为2,以此类推。另外,我还需要去掉两者之间的空格和定界符,我该怎么做呢?
from datetime import datetime
unique_dates = ["January 12,1988","February 11,1995","December 2,1992"]
ans = []
for val in unique_dates:
objDate = datetime.strptime(val, '%B %d,%Y')
ans.append(objDate.strftime('%d/%m/%Y'))
print(unique_dates, ans)
参考python中的datetime模块
首先使用 strptime
然后用 strftime
. 可以在一条线上做为:
from time import strptime, strftime
unique_dates = ["January 12,1988","February 11,1995","December 2,1992"]
[strftime('%d/%m/%Y', strptime(i, '%B %d,%Y')) for i in unique_dates]
>>> ['12/01/1988', '11/02/1995', '02/12/1992']