d = {'A1': ['C',
'2003-01-01 13:01:00',
'Lang',
'2012-06-02 07:00:00',
'55901',
'2001-09-05 00:00:00'],
'A2': ['Eds',
'2002-02-12 10:07:00',
'12-3-54']}
我有一个示例字典d
,其中包含日期,例如'2003-01-01 13:01:00'
,如上所示。 (我的实际 d
的 len
约为 700k,包含各种此类日期。)我想知道是否有一种方法可以将日期转换回单词。例如,'2003-01-01 13:01:00'
将变为 'January 1st, 2003 at 1:01pm'
。
我想要的输出是这样的
d = {'A1': ['C',
'January 1st, 2003 at 1:01pm',
'Lang',
'June 2nd, 2012 at 7:00am',
'55901',
'September 5th, 2001'],
'A2': ['Eds',
'February 12th, 2002 at 10:07am',
'12-3-54']}
我怎样才能完成这个输出?
最佳答案
import datetime
import json
d = {'A1': ['C',
'2003-01-01 13:01:00',
'Lang',
'2012-06-02 07:00:00',
'55901',
'2001-09-05 00:00:00'],
'A2': ['Eds',
'2002-02-12 10:07:00',
'12-3-54']}
suf = lambda n: "%d%s"%(n,{1:"st",2:"nd",3:"rd"}.get(n if n<20 else n%10,"th"))
daydict = dict(zip(range(1,32), [suf(n) for n in range(1,32)]))
#construct the datetime according to the form of 'January 1st, 2003 at 1:01pm'
for k, v in d.items():
index = 1
for item in v[1::2]:
tem = datetime.datetime.strptime(item, '%Y-%m-%d %H:%M:%S')
x = tem.hour-12 if tem.hour > 12 else tem.hour
y = 'pm' if tem.hour > 12 else 'am'
d[k][index] = ' '.join([tem.strftime('%B'), daydict[tem.day] + ',', str(tem.year), str(x)+':'+tem.strftime('%M')+y])
index += 2
print(json.dumps(d, indent=2))
输出
{
"A1": [
"C",
"January 1st, 2003 1:01pm",
"Lang",
"June 2nd, 2012 7:00am",
"55901",
"September 5th, 2001 0:00am"
],
"A2": [
"Eds",
"February 12th, 2002 10:07am",
"12-3-54"
]
}
关于python - 将数字日期转换为字典中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57780935/