gpt4 book ai didi

python - 将整数数组转换为日期对象

转载 作者:太空宇宙 更新时间:2023-11-03 13:37:05 25 4
gpt4 key购买 nike

我有一个整数数组,我想将其转换为日期类型的对象:

[[19480916 19480901 19480917 19480901 19480901 19481019]
[19480917 19480916 19481019 19480922 19480922 19490902]
[19481004 19480917 19481021 19480924 19481004 19501124]]

我有以下代码应该遍历数组并将每个数字转换为日期对象并将其附加到新列表:

Date_List = []
from datetime import date, datetime, timedelta
for s in myArray:
date1 = datetime(year=int(s[0:4]), month=int(s[4:6]), day=int(s[6:8]))
Date_List.append(date1)

当我运行它时,出现以下错误:

TypeError: only length-1 arrays can be converted to Python scalars.

有什么方法可以做到这一点吗?

最佳答案

使用 str() 将每个数字转换为字符串和 strptime()将字符串加载到 datetime 对象中:

from datetime import datetime

l = [
[19480916, 19480901, 19480917, 19480901, 19480901, 19481019],
[19480917, 19480916, 19481019, 19480922, 19480922, 19490902],
[19481004, 19480917, 19481021, 19480924, 19481004, 19501124]
]

for sublist in l:
print([datetime.strptime(str(item), "%Y%m%d") for item in sublist])

打印:

[datetime.datetime(1948, 9, 16, 0, 0), datetime.datetime(1948, 9, 1, 0, 0), datetime.datetime(1948, 9, 17, 0, 0), datetime.datetime(1948, 9, 1, 0, 0), datetime.datetime(1948, 9, 1, 0, 0), datetime.datetime(1948, 10, 19, 0, 0)]
[datetime.datetime(1948, 9, 17, 0, 0), datetime.datetime(1948, 9, 16, 0, 0), datetime.datetime(1948, 10, 19, 0, 0), datetime.datetime(1948, 9, 22, 0, 0), datetime.datetime(1948, 9, 22, 0, 0), datetime.datetime(1949, 9, 2, 0, 0)]
[datetime.datetime(1948, 10, 4, 0, 0), datetime.datetime(1948, 9, 17, 0, 0), datetime.datetime(1948, 10, 21, 0, 0), datetime.datetime(1948, 9, 24, 0, 0), datetime.datetime(1948, 10, 4, 0, 0), datetime.datetime(1950, 11, 24, 0, 0)]

关于python - 将整数数组转换为日期对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38102712/

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