将 strptime 函数应用于 pandas 系列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38797854/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:44:22  来源:igfitidea点击:

Applying strptime function to pandas series

pythonpandasstrptime

提问by thron of three

I have a pandas DataSeries that contains a string formatted date in the form of:

我有一个 Pandas DataSeries,它包含一个字符串格式的日期,格式为:

2016-01-14 11:39:54

2016-01-14 11:39:54

I would like to convert the string to a timestamp.

我想将字符串转换为时间戳。

I am using the applymethod to attemp to pass 'datetime.strptime' to each element of the series

我正在使用该apply方法尝试将“datetime.strptime”传递给系列的每个元素

date_series = date_string.apply(datetime.strptime, args=('%Y-%m-%d %H:%M:%S'))

date_series = date_string.apply(datetime.strptime, args=('%Y-%m-%d %H:%M:%S'))

When I run the code, I get the following error:

当我运行代码时,出现以下错误:

strptime() takes exactly 2 arguments (18 given)

strptime() takes exactly 2 arguments (18 given)

my questions are (1) am I taking the correct approach, (2) why is strptimeconverting my args into 18 arguments?

我的问题是 (1) 我是否采取了正确的方法,(2) 为什么strptime将我的 args 转换为 18 个参数?

回答by root

Use pd.to_datetime:

使用pd.to_datetime

date_series = pd.to_datetime(date_string)

In general it's best have your dates as Pandas' pd.Timestampinstead of Python's datetime.datetimeif you plan to do your work in Pandas. You may also want to review the Time Series / Date functionality documentation.

一般来说,如果您打算在 Pandas 中工作,最好将日期设为 Pandas,pd.Timestamp而不是 Python datetime.datetime。您可能还想查看时间序列/日期功能文档

As to why your applyisn't working, argsisn't being read as a tuple, but rather as a string that's being broken up into 17 characters, each being interpreted as a separate argument. To make it be read as a tuple, add a comma: args=('%Y-%m-%d %H:%M:%S',).

至于为什么你apply不工作,args不是作为一个元组读取,而是作为一个被分解为 17 个字符的字符串,每个字符都被解释为一个单独的参数。要使其被视为元组,请添加逗号:args=('%Y-%m-%d %H:%M:%S',)

This is standard behaviour in Python. Consider the following example:

这是 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'>