Python datetime.datetime.strptime要将字符串转换为datetime,则出现错误未转换日期:2
csv文件有18列,其中6列为“年”、“月”、“日”、“小时”、“分钟”、“秒”,数据类型均为INT,但“秒”列为float 首先,我将int和float类型转换为string,然后将它们浓缩,然后使用Python datetime.datetime.strptime要将字符串转换为datetime,则出现错误未转换日期:2,python,python-2.7,pandas,datetime,Python,Python 2.7,Pandas,Datetime,csv文件有18列,其中6列为“年”、“月”、“日”、“小时”、“分钟”、“秒”,数据类型均为INT,但“秒”列为float 首先,我将int和float类型转换为string,然后将它们浓缩,然后使用datetime.datetime.strtime将它们转换为datetype。但不知何故,它不起作用 它返回: File "/anaconda3/lib/python2.7/_strptime.py", line 335, in _strptime data_string[found.end()
datetime.datetime.strtime
将它们转换为datetype。但不知何故,它不起作用
它返回:
File "/anaconda3/lib/python2.7/_strptime.py", line 335, in _strptime
data_string[found.end():])
ValueError: unconverted data remains: 2
使用的代码是:
作为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)
你对熊猫的想法太多了。如果列的名称正确,则可以直接馈送到。此外,避免将Python的
datetime
模块用于熊猫:
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
注意datetime
值在内部存储为整数。避免您当前尝试的往返是有意义的:
str
,csv输入文件int
viapd.read\u csv
str
viapd.Series.apply
int
通过datetime.strtime