如何将字符串转换为日期 Pandas python TypeError:strptime() 不接受关键字参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22138932/
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-13 21:45:39  来源:igfitidea点击:

how to convert string to date pandas python TypeError: strptime() takes no keyword arguments

pythonstringdatepandas

提问by yoshiserry

I have a dataframe with some text dates in them. I would like to return the dates: year, month and day in separate columns. But in order to do that I need to first convert the text(from excel) to a date.

我有一个包含一些文本日期的数据框。我想在单独的列中返回日期:年、月和日。但是为了做到这一点,我需要首先将文本(从 excel)转换为日期。

The code I have now is

我现在的代码是

def convertdate(dstring):
    dt = time.strptime(dstring, date_format='%Y-%m-%d')
    return dt

However it returns an: TypeError: strptime() takes no keyword arguments

但是它返回一个: TypeError: strptime() takes no keyword arguments

Then instead of three separate functions for creating three separate columns, one for year, one for month, one for day.

然后,而不是用于创建三个单独列的三个单独的函数,一个用于年,一个用于月,一个用于日。

Once the string is a date time object (dt), I believe the code is: return dt.year, return dt.month, return dt.day.

一旦字符串是日期时间对象(dt),我相信代码是:return dt.year, return dt.month, return dt.day.

I would like one function which adds three columns to my dataframe, is this possible?

我想要一个向我的数据框添加三列的函数,这可能吗?

回答by falsetru

Pass the format string as a positional argument.

将格式字符串作为位置参数传递。

>>> import time
>>> def convertdate(dstring):
...     return time.strptime(dstring, '%Y-%m-%d')
...
>>> convertdate('2013-03-02')
time.struct_time(tm_year=2013, tm_mon=3, tm_mday=2, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=61, tm_isdst=-1)

BTW, time.strptimereturns time.struct_time. Its attributes are prefixed with tm_.

顺便说一句,time.strptime返回time.struct_time。它的属性以 为前缀tm_

More preferably you can use datetime.datetime.strptime:

更优选地,您可以使用datetime.datetime.strptime

>>> import datetime
>>> import pandas as pd
>>>
>>> def convertdate(dstring):
...     return datetime.datetime.strptime(dstring, '%Y-%m-%d')
...
>>> dt = convertdate('2013-03-02')
>>> dt
datetime.datetime(2013, 3, 2, 0, 0)
>>> pd.DataFrame([{'year': dt.year, 'month': dt.month, 'day': dt.day}])
   day  month  year
0    2      3  2013