python日期格式修改年月日_将日期字符串列表重新格式化为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.

First I make a series

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

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'

So I tried

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

This returned ['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.

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值