在python中将日期列转换为更高分辨率

我有一个其中的一列是:dftime


    time    

0   2014-01-01

1   2014-01-02

2   2014-01-03

3   2014-01-04

4   2014-01-05

     ...    ... 

我想将日期转换为粒度最多为几秒钟,例如,从 到 。最好的方法是什么?datetime2014-01-012014-01-01 11:00:00


我尝试了以下方法:


df['time'] = df['time'].astype('datetime64[ns]')

和这个:


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

然后这个:


df['time'] = [time.date() for time in df['time']]

奇怪的是,所有这些方法都没有发生任何事情。


一只名叫tom的猫
浏览 71回答 1
1回答

慕的地10843

你被你所看到的有点误导了。Pandas在时间戳上做一个地板,如果我们在给定的一天。00:00:00因此,当您制作一个&nbsp;df['time'] = pd.to_datetime(df['time'])然后进行从字符串到时间的转换,这是格式,但是仅当天之后的数据不是 时才会显示。举个例子:'%Y-%m-%d %H:%M:%S'00:00:00import pandas as pddf = pd.DataFrame(['2014/04/28 00:00:00', '2014-04-29', '2014-04-30'], columns=['time'])print(df)print(type(df['time'][0]))外:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; time0&nbsp; 2014/04/28 00:00:001&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;2014-04-292&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;2014-04-30<class 'str'>转换为 :pd.to_datetime()df['time'] = pd.to_datetime(df['time'])print(df)print(type(df['time'][0]))外:&nbsp; &nbsp; &nbsp; &nbsp; time0 2014-04-281 2014-04-292 2014-04-30<class 'pandas._libs.tslibs.timestamps.Timestamp'>print(df['time'][0])以系列的一个元素为例:外:2014-04-28 00:00:00现在同样,如果我们的时间戳之一不在:00:00:00df = pd.DataFrame(['2014/04/28 10:00:00', '2014-04-29', '2014-04-30'], columns=['time'])print(df)print(type(df['time'][0]))外:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; time0&nbsp; 2014/04/28 10:00:001&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;2014-04-292&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;2014-04-30<class 'str'>转换为 :pd.to_datetime()df['time'] = pd.to_datetime(df['time'])print(df)print(type(df['time'][0]))外:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;time0 2014-04-28 10:00:001 2014-04-29 00:00:002 2014-04-30 00:00:00<class 'pandas._libs.tslibs.timestamps.Timestamp'>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python