2017-10-06 40 views
0

我遇到了一些与Python的dateutil.parser有关的问题。ValueError:未知的字符串格式dateparser python CSV

我有一个CSV文件,我负责阅读和显示月份。

一个组可能有29 Jun 2017 1600,而其中一些有“2017年6月29日1600小时”,只要数据有额外的字符串,如hrs。它会显示此错误:ValueError: Unknown string format

这里是我的代码:dt = dateutil.parser.parse(data.GetDataType(frequency))

如何删除hrs或允许程序能够流畅运行?

回答

0
# full, working, python 3 solution 
# modified to work on strings with or without "hrs" 
# "$" in re.sub means hrs only matches at end of input string 
# I hope you read this, because I can change this answer, but I cannot comment :-D 

import re 
from datetime import datetime 

stringDateIn1 = "29 Jun 2017 1601" 
stringDateIn2 = "29 Jun 2017 1602 hrs" 

stringDateFixed1 = re.sub(" hrs$", "", stringDateIn1) 
stringDateFixed2 = re.sub(" hrs$", "", stringDateIn2) 

datetimeOut1 = datetime.strptime(stringDateFixed1, '%d %b %Y %H%M') 
datetimeOut2 = datetime.strptime(stringDateFixed2, '%d %b %Y %H%M') 

print("date = " + str(datetimeOut1)) 
print("date = " + str(datetimeOut2)) 
+0

有些数据有小时,有些则没有。我如何确保它可以在有或没有小时的情况下顺利运行?谢谢您的帮助! –

相关问题