Python 将 DataFrame 列类型从字符串转换为日期时间,dd/mm/yyyy 格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17134716/
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
Convert DataFrame column type from string to datetime, dd/mm/yyyy format
提问by perigee
How can I convert a DataFrame column of strings (in dd/mm/yyyyformat) to datetimes?
如何将字符串的 DataFrame 列(以dd/mm/yyyy格式)转换为日期时间?
采纳答案by Andy Hayden
The easiest way is to use to_datetime:
最简单的方法是使用to_datetime:
df['col'] = pd.to_datetime(df['col'])
It also offers a dayfirstargument for European times (but beware this isn't strict).
它还dayfirst为欧洲时代提供了一个论据(但要注意这不是严格的)。
Here it is in action:
这是在行动:
In [11]: pd.to_datetime(pd.Series(['05/23/2005']))
Out[11]:
0 2005-05-23 00:00:00
dtype: datetime64[ns]
You can pass a specific format:
您可以传递特定格式:
In [12]: pd.to_datetime(pd.Series(['05/23/2005']), format="%m/%d/%Y")
Out[12]:
0 2005-05-23
dtype: datetime64[ns]
回答by sigurdb
If your date column is a string of the format '2017-01-01' you can use pandas astype to convert it to datetime.
如果您的日期列是格式为“2017-01-01”的字符串,您可以使用 pandas astype 将其转换为日期时间。
df['date'] = df['date'].astype('datetime64[ns]')
df['date'] = df['date'].astype('datetime64[ns]')
or use datetime64[D] if you want Day precision and not nanoseconds
或使用 datetime64[D] 如果您想要 Day 精度而不是纳秒
print(type(df_launath['date'].iloc[0]))
print(type(df_launath['date'].iloc[0]))
yields
产量
<class 'pandas._libs.tslib.Timestamp'>the same as when you use pandas.to_datetime
<class 'pandas._libs.tslib.Timestamp'>与使用 pandas.to_datetime 时相同
You can try it with other formats then '%Y-%m-%d' but at least this works.
您可以尝试使用其他格式然后 '%Y-%m-%d' 但至少这是有效的。
回答by Ekhtiar
You can use the following if you want to specify tricky formats:
如果要指定棘手的格式,可以使用以下内容:
df['date_col'] = pd.to_datetime(df['date_col'], format='%d/%m/%Y')
More details on formathere:
更多细节在format这里:
回答by abhyudayasrinet
If you have a mixture of formats in your date, don't forget to set infer_datetime_format=Trueto make life easier
如果您的约会对象混合了多种格式,请不要忘记设置infer_datetime_format=True让生活更轻松
df['date'] = pd.to_datetime(df['date'], infer_datetime_format=True)
df['date'] = pd.to_datetime(df['date'], infer_datetime_format=True)
Source: pd.to_datetime
or if you want a customized approach:
或者如果你想要一个定制的方法:
def autoconvert_datetime(value):
formats = ['%m/%d/%Y', '%m-%d-%y'] # formats to try
result_format = '%d-%m-%Y' # output format
for dt_format in formats:
try:
dt_obj = datetime.strptime(value, dt_format)
return dt_obj.strftime(result_format)
except Exception as e: # throws exception when format doesn't match
pass
return value # let it be if it doesn't match
df['date'] = df['date'].apply(autoconvert_datetime)

