gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:05:11 24 4
gpt4 key购买 nike

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

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

关于python - 将字符串中的日期列表转换为 Python 中的月、日、年,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32407147/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com