ホーム>source

I have two columns, one has type datetime64 and datetime.time. The first column has the day and the second one the hour and minutes. I am having trouble parsing them:

Leistung_0011
       ActStartDateExecution ActStartTimeExecution
0             2016-02-17              11:00:00
10            2016-04-15              07:15:00
20            2016-06-10              10:30:00

Leistung_0011 ['Start_datetime'] = pd.to_datetime(Leistung_0011 ['ActStartDateExecution']。astype(str)+ '' + Leistung_0011 ['ActStartTimeExecution']。astype(str))

ValueError: ('Unknown string format:', 'NaT 00:00:00')

あなたの答え
  • 解決した方法 # 1

    str に変換できます   pd.to_datetime に渡す前に空白で結合します :

    df['datetime'] = pd.to_datetime(df['day'].astype(str) + ' ' + df['time'].astype(str))
    print(df, df.dtypes, sep='\n')
    #          day      time            datetime
    # 0 2018-01-01  15:00:00 2018-01-01 15:00:00
    # 1 2015-12-30  05:00:00 2015-12-30 05:00:00
    # day         datetime64[ns]
    # time                object
    # datetime    datetime64[ns]
    # dtype: object
    
    

    セットアップ

    from datetime import datetime
    df = pd.DataFrame({'day': ['2018-01-01', '2015-12-30'],
                       'time': ['15:00', '05:00']})
    df['day'] = pd.to_datetime(df['day'])
    df['time'] = df['time'].apply(lambda x: datetime.strptime(x, '%H:%M').time())
    print(df['day'].dtype, type(df['time'].iloc[0]), sep='\n')
    # datetime64[ns]
    # <class 'datetime.time'>
    
    

    秒を含む完全な例:

    import pandas as pd
    from io import StringIO
    x = StringIO("""       ActStartDateExecution ActStartTimeExecution
    0             2016-02-17              11:00:00
    10            2016-04-15              07:15:00
    20            2016-06-10              10:30:00""")
    df = pd.read_csv(x, delim_whitespace=True)
    df['ActStartDateExecution'] = pd.to_datetime(df['ActStartDateExecution'])
    df['ActStartTimeExecution'] = df['ActStartTimeExecution'].apply(lambda x: datetime.strptime(x, '%H:%M:%S').time())
    df['datetime'] = pd.to_datetime(df['ActStartDateExecution'].astype(str) + ' ' + df['ActStartTimeExecution'].astype(str))
    print(df.dtypes)
    ActStartDateExecution    datetime64[ns]
    ActStartTimeExecution            object
    datetime                 datetime64[ns]
    dtype: object
    
    

  • 前へ java - JPAクエリ:サブクエリをグループ化条件に結合する
  • 次へ vb.net - ファイル名の最大文字数を設定するにはどうすればよいですか?