2015-09-04 23 views
1

轉換日期的列表中串月,日,年我有日期的列表中,看起來像這樣的字符串:在Python

Date_List 
Out[83]: 
['2015-08-24 00:00:00', 
'2015-08-30 00:00:00', 
'2015-08-22 00:00:00', 
'2015-08-21 00:00:00', 
'2015-08-25 00:00:00', 
'2015-08-29 00:00:00'] 

我希望它是格式如下:

Date_List 
Out[83]: 
['08-24-2015', 
'08-30-2015', 
'08-22-2015', 
'08-21-2015', 
'08-25-2015', 
'08-29-2015'] 

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

這將返回

Date_List 
Out[85]: 
['08-24 00:00:00-2015', 
'08-30 00:00:00-2015', 
'08-22 00:00:00-2015', 
'08-21 00:00:00-2015', 
'08-25 00:00:00-2015', 
'08-29 00:00:00-2015'] 

有人知道如何轉換,並忽略00:00:00

我也試過

​​

但這輸出生成的對象?

Date_List 
Out[91]: <generator object <genexpr> at 0x2047A5A8> 

這意味着,如果我運行代碼,我得到這個錯誤:TypeError: <generator object <genexpr> at 0x1FBCFC38> is not JSON serializable

回答

4

你非常接近;你只需要在最後一行使用列表理解而不是生成器表達式。

Date_List = (datetime.datetime.strptime(i, "%Y-%m-%d %H:%M:%S") for i in Date_List) 
Date_List = [datetime.datetime.strftime(i, "%m-%d-%Y") for i in Date_List] 

我將它清理乾淨,像這樣:

from datetime import datetime 
from pprint import pprint 

timestamps = [ 
    '2015-08-24 00:00:00', 
    '2015-08-30 00:00:00', 
    '2015-08-22 00:00:00', 
    '2015-08-21 00:00:00', 
    '2015-08-25 00:00:00', 
    '2015-08-29 00:00:00', 
    ] 

dates = (datetime.strptime(ts, '%Y-%m-%d %H:%M:%S') for ts in timestamps) 
date_strings = [datetime.strftime(d, '%m-%d-%Y') for d in dates] 

pprint(date_strings) 

輸出:

['08-24-2015', 
'08-30-2015', 
'08-22-2015', 
'08-21-2015', 
'08-25-2015', 
'08-29-2015'] 

這裏有一個稍微更廣義的方式來做到這一點:

from datetime import datetime 
from pprint import pprint 


def convert_timestamp(ts, from_pattern, to_pattern): 
    dt = datetime.strptime(ts, from_pattern) 
    return datetime.strftime(dt, to_pattern) 


timestamps = [ 
    '2015-08-24 00:00:00', 
    '2015-08-30 00:00:00', 
    '2015-08-22 00:00:00', 
    '2015-08-21 00:00:00', 
    '2015-08-25 00:00:00', 
    '2015-08-29 00:00:00', 
    ] 

date_strings = [convert_timestamp(ts, '%Y-%m-%d %H:%M:%S', '%m-%d-%Y') 
       for ts in timestamps] 

pprint(date_strings) 

輸出:

['08-24-2015', 
'08-30-2015', 
'08-22-2015', 
'08-21-2015', 
'08-25-2015', 
'08-29-2015'] 
+0

啊!哇,我不知道生成器表達式和列表解析之間的區別,很好理解! – jenryb

0

這應該做的伎倆:

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

你不需要str(x),因爲它已經是一個字符串。然後你輸入split()這個字符串,默認情況下這個字符串會以空格分隔,然後取第一部分([0])。然後你在連字符上寫上split('-')

2

編輯:訂單固定。

EDIT2:零填充固定保羅的建議後

嘗試:

from dateutil import parser 
map(
    lambda d: "{0:02}-{1:02}-{2}".format(d.month, d.day, d.year), 
    map(
     lambda d: parser.parse(d), 
     dates 
    ) 
) 

["{0:02}-{1:02}-{2}".format(d.month, d.day, d.year) for d in map(lambda d: parser.parse(d), dates)] 
+0

什麼是......? –

+0

您沒有按請求的順序放置日期組件。編輯:你不填充1位數組件。 –

+0

感謝評論@PauloAlmeida,修正了訂單。 – sjosund