我有一堆这种形式的日期字符串:-
30th November 2009
31st March 2010
30th September 2010
我希望他们这样:-
YYYYMMDD
目前,我正在这样做:-
parsed_date = "30th November 2009"
part = parsed_date.split(' ')
daymonth = part[0].strip(string.ascii_letters)
mytime = daymonth+" "+part[1]+" "+part[2]
time_format = "%d %B %Y"
cdate = time.strptime(mytime, time_format)
newdate = str(cdate[0])+str(cdate[1])+str(cdate[2])
它有效,但是我敢肯定有更好的方法...
最佳答案
尝试dateutil:
from dateutil import parser
dates = ['30th November 2009', '31st March 2010', '30th September 2010']
for date in dates:
print parser.parse(date).strftime('%Y%m%d')
输出:
20091130
20100331
20100930
或者,如果您想使用标准的
datetime
模块来做到这一点:from datetime import datetime
dates = ['30th November 2009', '31st March 2010', '30th September 2010']
for date in dates:
part = date.split()
print datetime.strptime('%s %s %s' % (part[0][:-2]), part[1], part[2]), '%d %B %Y').strftime('%Y%m%d')
关于python - 将日期字符串转换为YYYYMMDD,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6941965/