在数据框中将所有日期更改为标准日期时间 [英] changing all dates to standard date time in dataframe

查看:358
本文介绍了在数据框中将所有日期更改为标准日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有日期列的数据框,它看起来像这样.有多个日期列,例如结束日期,会计年度日期等.

I have a dataframe with date column where it looks like this. There are more than one date column such as end date, fiscal year date etc.

Plan Start Date
8/16/2017 0:00
5/31/2017 0:00
5/31/2017 0:00
5/31/2017 0:00
5/31/2017 0:00
4/21/2016 0:00
2/25/2016 0:00
12/15/2016 0:00
12/15/2016 0:00
12/15/2016 0:00
42373
42373
42367
42367
42367
42367
42460
42460
42460
42460
42460
42759
42333

我正在尝试编写一个函数,该函数基本上将那些整数更改为适当的日期格式,并将此列的格式设置为datetime [64].此列格式是当前对象类型.

I am trying to write a function where it basically changes those integrers to appropriate date format and format this column as datetime[64]. this column format is current object type.

我写了下面的函数

def change_date_df(df):
    format_dates_df = [col for col in df.columns if 'Date' in col];
    for date in format_dates_df:
        df[date] = pd.to_datetime(df[date]).apply(lambda x: x.strftime('%d-%m-%y')if not pd.isnull(x) else '');
    return df;

现在回赠

ValueError: mixed datetimes and integers in passed array

我猜这些数字没有转换为日期.但我不确定我还能如何调整我的代码.

Im guessing these numbers are not being converted to dates. but Im not sure how else i can adjust my code.

有什么主意吗?

亚当

推荐答案

引用或者,如果您有一列对象-

Or, if you have a column of objects -

df['Plan Start Date'].astype(str).str.isdigit()

接下来,使用apply将函数应用于行的子集-

Next, apply the function on a subset of the rows using apply -

df.loc[m, 'Plan Start Date'] = \
df.loc[m, 'Plan Start Date']\
  .astype(int)\
  .apply(from_excel_ordinal)

最后,使用pd.to_datetime将整个列转换为日期时间,得到统一的结果-

Finally, convert the entire column to datetime using pd.to_datetime, giving a uniform result -

df['Plan Start Date'] = pd.to_datetime(df['Plan Start Date'], errors='coerce')

df

   Plan Start Date
0       2017-08-16
1       2017-05-31
2       2017-05-31
3       2017-05-31
4       2017-05-31
5       2016-04-21
6       2016-02-25
7       2016-12-15
8       2016-12-15
9       2016-12-15
10      2016-01-04
11      2016-01-04
12      2015-12-29
13      2015-12-29
14      2015-12-29
15      2015-12-29
16      2016-03-31
17      2016-03-31
18      2016-03-31
19      2016-03-31
20      2016-03-31
21      2017-01-24
22      2015-11-25

这篇关于在数据框中将所有日期更改为标准日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆