将日期字符串列表重新格式化为 Python 中的日、月、年

Reformatting a list of date strings to day, month, year in Python

我想更改列表中字符串的格式。它们是日期但已转换为字符串。

我找遍了这个解决方案,但似乎只有一个元素的答案。

首先我做一个系列

Date_List = df.loc['receiveddate']
print Date_List

Element1                               2015-06-26
Element2                               2015-06-25
Element3                               2015-06-26
Element4                               2015-06-25
Element5                               2015-06-25
Element6                               2015-07-01

然后我把它转换成一个列表。

Date_List = [str(i) for i in Date_List]

这给了我

['2015-06-26', '2015-06-25', '2015-06-26', '2015-06-25', '2015-06-25', '2015-07-01']

相反,我想要一个包含日、月、年的字符串列表

['06-26-2015', '06-25-2015...etc.]

我发现最常见的建议是使用 strftime。尝试 Date_List = (datetime.datetime.strptime(i, "%B %d-%Y") for i in Date_List) 刚给了我 ValueError: time data '2015-06-26' does not match format '%B %d-%Y'

所以我尝试了

Date_List = (datetime.datetime.strptime(i, "%Y-%m-%d") for i in Date_List)

这返回了['2015-06-26 00:00:00', '2015-06-25 00:00:00', '2015-06-26 00:00:00', '2015-06-25 00:00:00', '2015-06-25 00:00:00', '2015-07-01 00:00:00']

有人知道如何重新格式化列表吗?或者更早,重新格式化系列?谢谢。

你快到了。 datetime.datetime.strptime 将字符串转换为 datetime 对象。您需要 datetime.datetime.strftime 将其转换回字符串:

Date_List = (datetime.datetime.strptime(i, "%Y-%m-%d") for i in Date_List)
Date_List = (datetime.datetime.strftime(i, "%m-%d-%Y") for i in Date_List)

你甚至不需要在这里使用 datetime。只需将这些对象映射到将它们转换为字符串并在 - 上拆分它们的函数,然后使用 str.format():

Date_List = ['{}-{}-{}'.format(m,d,y) for y, m, d in map(lambda x: str(x).split('-'), Date_List)]

此外,从您的代码片段来看,您似乎首先想要月份,而不是日期。

你可以通过字符串的角度来解决

New_Date_List = [d[8:10]+"-"+d[5:7]+"-"+d[:4] for d in Date_List]

将你的理解改为

import datetime
Date_List = [datetime.datetime.strptime(str(i), '%Y-%m-%d').strftime('%m-%d-%Y') for i in Date_List]

正则表达式提供了一个非常简单的解决方案:

>>> import re
>>> re.sub(r'(\d{4})-(\d{2})-(\d{2})', r'--', '2015-06-25')
'06-25-2015'

虽然不漂亮,但应该可以生成月-日-年列表。

New_Date_List = [[d][5:7] + '-' + Date_List[d][-2:] + '-' + Date_List[d][:4] for d in Date_List]