[英]Converting a list of dates in string to Month, Day, Year in 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 = (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)
但這會輸出一個生成器對象?
Date_List
Out[91]: <generator object <genexpr> at 0x2047A5A8>
這意味着如果我運行代碼,將出現以下錯誤: TypeError: <generator object <genexpr> at 0x1FBCFC38> is not JSON serializable
你很親近 您只需要在最后一行使用列表推導,而不要使用生成器表達式。
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']
編輯:定單。
編輯2:保羅的建議后固定零填充
嘗試:
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)]
這應該可以解決問題:
['{}-{}-{}'.format(m,d,y) for y, m, d in map(lambda x: x.split()[0].split('-'), Date_List)]
您不需要str(x)
因為它已經是一個字符串。 然后,您對字符串進行split()
該字符串默認情況下在空格上分割,並采用第一部分( [0]
)。 然后,在連字符上split('-')
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.