ValueError:未知的字符串格式dateparser python CSV

时间:2017-10-06 14:37:36

标签: python csv graph date-parsing

我遇到了Python dateutil.parser的一些问题。

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

如果数据包含其他字符串(如hrs),则某个群组可能会29 Jun 2017 1600,而某些群组可能会在2017年6月29日1600小时"它将显示此错误:ValueError: Unknown string format

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

如何删除hrs或允许程序顺利运行?

1 个答案:

答案 0 :(得分: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 ) )