gpt4 book ai didi

python - 将日期从 numpyarray 转换为日期时间类型 -> 出现神秘错误

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

我使用 numpy.loadtxt 函数加载文件 f 并希望提取一些日期。日期的格式如下:15.08。 - 2011年8月21日

numpyarr = loadtxt(f, dtype=str, delimiter=";", skiprows = 1)  

alldate = numpyarr[:,0][0]

dat = datetime.datetime.strptime(alldate,"%d.%m. - %d.%m.%Y")

这是整个错误:

Traceback (most recent call last):
File "C:\PYTHON\Test DATETIME_2.py", line 52, in <module>
dat = datetime.datetime.strptime(alldate,"%d.%m. - %d.%m.%Y")

File "C:\Python27\lib\_strptime.py", line 308, in _strptime
format_regex = _TimeRE_cache.compile(format)

File "C:\Python27\lib\_strptime.py", line 265, in compile
return re_compile(self.pattern(format), IGNORECASE)

File "C:\Python27\lib\re.py", line 190, in compile
return _compile(pattern, flags)

File "C:\Python27\lib\re.py", line 242, in _compile
raise error, v # invalid expression
sre_constants.error: redefinition of group name 'd' as group 3; was group 1

有人知道发生了什么吗?

最佳答案

datetime 保存单个日期和时间,而您的字段包含两个日期并尝试将它们提取到单个变量中。具体来说,您收到的错误是因为您使用了 %d%m 两次。

您可以尝试以下方法:

a = datetime.datetime.strptime(alldate.split('-')[0],"%d.%m. ")
b = datetime.datetime.strptime(alldate.split('-')[1]," %d.%m.%Y")
a = datetime.datetime(b.year, a.month, a.day)

(这不是最好的代码,但它证明了字符串中隐藏着两种不同格式的两个日期这一事实)。

关于python - 将日期从 numpyarray 转换为日期时间类型 -> 出现神秘错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26424195/

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