pandas 在python pandas中将时间对象转换为日期时间格式

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

Convert time object to datetime format in python pandas

pythonpython-3.xpandasdatetimedataframe

提问by Nadeem Haque

I have a dataset of column name DateTimehaving dtype object.

我有一个列名DateTime具有 dtype object的数据集。

df['DateTime'] = pd.to_datetime(df['DateTime'])

I have used the above code to convert to datetimeformat then did a split in the column to have Dateand Timeseparately

我用上面的代码转换为日期时间格式,然后做在列拆分有日期时间分别

df['date'] = df['DateTime'].dt.date
df['time'] = df['DateTime'].dt.time

but after the split the format changes to object type and while converting it to datetime it showing error for the timecolumn name as: TypeError: is not convertible to datetime

但是在拆分后,格式更改为对象类型,并且在将其转换为日期时间时,它显示时间列名称的错误为:TypeError: is not convertible to datetime

How to convert it to datetime format the timecolumn

如何将其转换为日期时间格式的时间

采纳答案by jezrael

You can use combinein list comprehension with zip:

您可以combine在列表理解中使用zip

df = pd.DataFrame({'DateTime': ['2011-01-01 12:48:20', '2014-01-01 12:30:45']})
df['DateTime'] = pd.to_datetime(df['DateTime'])

df['date'] = df['DateTime'].dt.date
df['time'] = df['DateTime'].dt.time

import datetime
df['new'] = [datetime.datetime.combine(a, b) for a, b in zip(df['date'], df['time'])]
print (df)

             DateTime        date      time                 new
0 2011-01-01 12:48:20  2011-01-01  12:48:20 2011-01-01 12:48:20
1 2014-01-01 12:30:45  2014-01-01  12:30:45 2014-01-01 12:30:45

Or convert to strings, join together and convert again:

或转换为字符串,连接在一起并再次转换:

df['new'] = pd.to_datetime(df['date'].astype(str) + ' ' +df['time'].astype(str))
print (df)
             DateTime        date      time                 new
0 2011-01-01 12:48:20  2011-01-01  12:48:20 2011-01-01 12:48:20
1 2014-01-01 12:30:45  2014-01-01  12:30:45 2014-01-01 12:30:45

But if use floorfor remove times with converting times to timedeltas then use +only:

但是,如果floor用于将时间转换为 timedeltas 的删除时间,则+仅使用:

df['date'] = df['DateTime'].dt.floor('d')
df['time'] = pd.to_timedelta(df['DateTime'].dt.strftime('%H:%M:%S'))

df['new'] = df['date'] + df['time']
print (df)

             DateTime       date     time                 new
0 2011-01-01 12:48:20 2011-01-01 12:48:20 2011-01-01 12:48:20
1 2014-01-01 12:30:45 2014-01-01 12:30:45 2014-01-01 12:30:45

回答by jpp

How to convert it back to datetime format the time column

如何将其转换回日期时间格式的时间列

There appears to be a misunderstanding. Pandas datetimeseries mustinclude date and time components. This is non-negotiable. You can simply use pd.to_datetimewithout specifying a date and use the default 1900-01-01date:

似乎有误会。Pandasdatetime系列必须包含日期和时间组件。这是没有商量余地的。您可以简单地使用pd.to_datetime而不指定日期并使用默认1900-01-01日期:

# date from jezrael

print(pd.to_datetime(df['time'], format='%H:%M:%S'))

0   1900-01-01 12:48:20
1   1900-01-01 12:30:45
Name: time, dtype: datetime64[ns]

Or use another date component, for example today's date:

或者使用另一个日期组件,例如今天的日期:

today = pd.Timestamp('today').strftime('%Y-%m-%d')
print(pd.to_datetime(today + ' '  + df['time'].astype(str)))

0   2018-11-25 12:48:20
1   2018-11-25 12:30:45
Name: time, dtype: datetime64[ns]

Or recombine from your dateand timeseries:

或者从你的datetime系列中重新组合:

print(pd.to_datetime(df['date'].astype(str) + ' ' + df['time'].astype(str)))

0   2011-01-01 12:48:20
1   2014-01-01 12:30:45
dtype: datetime64[ns]