Skip to main content
 首页 » 编程设计

python之将字符串中的日期列表转换为 Python 中的月、日、年

2025年05月04日20lvdongjie

我有一个字符串形式的日期列表,如下所示:

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