thr*_*ree 6 python strptime pandas
我有一个pandas DataSeries,其中包含日期格式的字符串格式:
2016-01-14 11:39:54
我想将字符串转换为时间戳。
我正在apply尝试尝试将'datetime.strptime'传递给系列的每个元素的方法
date_series = date_string.apply(datetime.strptime, args=('%Y-%m-%d %H:%M:%S'))
运行代码时,出现以下错误:
strptime() takes exactly 2 arguments (18 given)
我的问题是(1)我是否采用正确的方法,(2)为什么strptime将我的args转换为18个参数?
date_series = pd.to_datetime(date_string)
Run Code Online (Sandbox Code Playgroud)
通常,如果您打算在Pandas中进行工作,最好将日期设为Pandas,pd.Timestamp而不是Python datetime.datetime。您可能还需要查看时间序列/日期功能文档。
至于为什么你apply不工作,args不是作为一个元组读取,而是作为一个被分解为17个字符的字符串,每个字符串都被解释为一个单独的参数。要使其以元组形式阅读,请添加逗号:args=('%Y-%m-%d %H:%M:%S',)。
这是Python中的标准行为。考虑以下示例:
x = ('a')
y = ('a',)
print('x info:', x, type(x))
print('y info:', y, type(y))
x info: a <class 'str'>
y info: ('a',) <class 'tuple'>
Run Code Online (Sandbox Code Playgroud)