将日期字符串列表重新格式化为Python中的日,月,年 [英] Reformatting a list of date strings to day, month, year in Python

查看:659
本文介绍了将日期字符串列表重新格式化为Python中的日,月,年的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更改列表中字符串的格式。他们是日期,但已被转换成字符串。

I want to change the format of strings in a list. They are dates but have been converted into strings.

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

I have looked all over for this solution, but there seem to only be answers for a single element.

首先我做一个系列

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

然后我将它转换成列表。

Then I convert it into a list.

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

这给了我

which gives me

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

相反,我想要一个日期,月份,年份的字符串列表

Instead, I want a list of strings that go day, month, year

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

我发现最常见的建议是使用strftime。尝试 Date_List =(datetime.datetime.strptime(i,%B%d-%Y)为我在Date_List)给了我 ValueError :时间数据'2015-06-26'不符合格式'%B%d-%Y'

I've found that the most common suggestion is to use strftime. Trying Date_List = (datetime.datetime.strptime(i, "%B %d-%Y") for i in Date_List) Just gave me ValueError: time data '2015-06-26' does not match format '%B %d-%Y'

(Date_List)(datetime.datetime.strptime(i,%Y-%m-%d)为我在Date_List $)

So I tried

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']

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

Does anybody know how to reformat the list? Or perhaps earlier, reformatting the Series? Thank you.

推荐答案

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

You don't even need to use datetime here. Just map those objects to a function that turns them into strings and splits them on the -, then use str.format():

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

另外,从你的代码片段看起来你想要的是第一个月,而不是一天。

Also, from your code snippet it looks like you want the month first, not the day.

这篇关于将日期字符串列表重新格式化为Python中的日,月,年的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆