csv文件有18列,其中6列分别是'年','月','日','小时','分钟','秒',其数据类型均为INT,除了列'秒'是 float 。
首先,我将int和float类型转换为字符串,然后将它们连接起来,然后使用datetime.datetime.strptime
将它们转换为datetype。但不知怎的,它不起作用。
它返回:
File "/anaconda3/lib/python2.7/_strptime.py", line 335, in _strptime
data_string[found.end():])
ValueError: unconverted data remains: 2
使用的代码是: 将 pandas 导入为 pd 导入时间 导入日期时间
df=pd.read_csv('/Users/song/PycharmProjects/AAA/nppanda/LASTROW/LASTROW_GTE Aurich.csv')
df.dropna(how='any')
df.columns=['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17']
df['18']=df['12'].apply(lambda x:str(x))
df['19']=df['13'].apply(lambda x:str(x))
df['20']=df['14'].apply(lambda x:str(x))
df['21']=df['15'].apply(lambda x:str(x))
df['22']=df['16'].apply(lambda x:str(x))
df['23']=df['17'].apply(lambda x:str(x))
df['24']=df['18'].str.cat(df['19'],sep='-')
df['24']=df['24'].str.cat(df['20'],sep='-')
df['24']=df['24'].str.cat(df['21'],sep=' ')
df['24']=df['24'].str.cat(df['22'],sep=':')
df['24']=df['24'].str.cat(df['23'],sep=':')
def has_seconds(a_string):
if a_string.find('.')!=-1:
transtime=datetime.datetime.strptime(a_string,'%Y-%m-%d %H:%M:%S.%f')
elif a_string.find('.')==-1:
transtime=datetime.datetime.strptime(a_string,'%Y-%m-%d %H:%M:%S')
return transtime
df['25']=df['24'].apply(has_seconds)
最佳答案
你对 Pandas 的想法想得太多了。如果您的列命名适当,您可以直接输入 pd.to_datetime
。此外,避免将 Python 的 datetime
模块与 Pandas 一起使用:
df = pd.DataFrame([[2015, 12, 20, 15, 10, 3.1234],
[2018, 5, 15, 10, 12, 65.432]],
columns=['year','month','day','hours','minutes','seconds'])
df['datetime'] = pd.to_datetime(df)
print(df)
year month day hours minutes seconds datetime
0 2015 12 20 15 10 3.1234 2015-12-20 15:10:03.123400
1 2018 5 15 10 12 65.4320 2018-05-15 10:13:05.432000
注意日期时间
值在内部存储为整数。避免您当前正在尝试的往返是有意义的:
str
,csv 输入文件int
通过pd.read_csv
str
通过pd.Series.apply
int
通过datetime.strptime
。
所有这些都非常昂贵且不必要。
关于python - datetime.datetime.strptime 将字符串转换为日期时间时出现错误 未转换日期 remands : 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53154628/