我需要转换是这样的:如何日期后缀转换成另一种格式,在python
Mar 31st, 2014
Aug 13th, 2014
Sep 2nd, 2014
分为:
31/03/2014
13/08/2014
2/09/2014
我一直在寻找strptime但后缀在获得方式。 谢谢。
我需要转换是这样的:如何日期后缀转换成另一种格式,在python
Mar 31st, 2014
Aug 13th, 2014
Sep 2nd, 2014
分为:
31/03/2014
13/08/2014
2/09/2014
我一直在寻找strptime但后缀在获得方式。 谢谢。
您可以使用dateutil
模块:
>>> from dateutil.parser import parse
>>> s = 'Mar 31st, 2014'
>>> parse(s)
datetime.datetime(2014, 3, 31, 0, 0)
你可以定义自己的函数来做到这一点:
d = {'Jan': '01', 'Feb': '02', 'Mar': '03', 'Apr': '04', 'May': '05', 'Jun': '06', 'Jul': '07', 'Aug': '08', 'Sep': '09', 'Oct': '10', 'Nov': '11', 'Dec': '12'}
def parser(date):
date = date.split() # date = ['Mar', '31st,', '2014']
for i, elem in enumerate(date):
if i == 0:
month = d[elem] # month = '03'
elif i == 1:
date = elem[:len(elem) - 3] # date = '31'
else:
year = elem # year = '2014'
return date + "/" + month + "/" + year # '31/03/2014'
print parser('Mar 31st, 2014')
这将返回31/03/2014
使用标准的模块的主要问题对于带有后缀的日子(我的意思是'st','nd','th')没有格式选项,没有前导零的情况下没有任何选项。 至于后缀,你可以安全地删除它们,因为它们不会出现在月份名称中。至于没有前导零的那天,我们可以通过明确选择日期部分来构造字符串。
from datetime import datetime
def convert(dt_string, in_format='%b %d, %Y', out_format='{0.day}{0:/%m/%Y}'):
for suffix in ('st', 'nd', 'rd', 'th'):
dt_string = dt_string.replace(suffix, '')
return out_format.format(datetime.strptime(dt_string, in_format))
dates = ['Mar 31st, 2014', 'Aug 13th, 2014', 'Sep 2nd, 2014']
print map(convert, dates)
我会用下面的方法。
import datetime
import re
# Collect all dates into a list.
dates = [ 'Mar 31st, 2014', 'Aug 13th, 2014', 'Sep 2nd, 2014' ]
# Compile a pattern to replace alpha digits in date to empty string.
pattern = re.compile('(st|nd|rd|th|,)')
# Itegrate through the list and replace the old format to the new one.
for offset, date in enumerate(dates):
date = pattern.sub('', date)
date = datetime.datetime.strptime(date, '%b %d %Y')
dates[offset] = str(date.day) + '/' + str(date.month) + '/' + str(date.year)
print(dates[offset]);
谢谢! a = parse(date) released = a.day .__ str __()+“/”+ a.month .__ str __()+“/”+ a.year .__ str __() – 2014-09-02 04:46:48
您的月份不会为零,如您在所需示例输出中显示的那样。此外,您显式使用私有方法('__str__')是一个不好的迹象。使用''{0.day} {0:/%m /%Y}'。格式(a)'而不是 – 2014-09-02 05:06:32
为什么它在这种特定情况下不好? – 2014-09-02 05:12:03