熊猫-将float转换为正确的日期时间或时间对象

时间:2019-01-22 17:23:43

标签: python pandas datetime time

我有一个观测数据集,其中包含天气信息。每列包含特定字段,其中日期和时间位于两个单独的列中。时间列包含每小时的时间,例如0000、0600 ..直至2300。我要尝试做的是基于某些时间范围(例如0000 UTC到0600 UTC之间)过滤数据集。当我尝试读取pandas数据框中的数据文件时,默认情况下,时间列以float形式读取。当我尝试将其转换为datatime对象时,它会产生一种无法转换的格式。代码示例如下:

import pandas as pd
import datetime as dt 
df = pd.read_excel("test.xlsx") 
df.head()

产生以下结果:

       tdate   itime moonph  speed   ...          qnh  windir maxtemp mintemp
0  01-Jan-17  1000.0    NM7      5   ...    $1,011.60    60.0  $32.60  $22.80
1  01-Jan-17  1000.0    NM7      2   ...    $1,015.40   999.0  $32.60  $22.80
2  01-Jan-17  1030.0    NM7      4   ...    $1,015.10    60.0  $32.60  $22.80
3  01-Jan-17  1100.0    NM7      3   ...    $1,014.80   999.0  $32.60  $22.80
4  01-Jan-17  1130.0    NM7      5   ...    $1,014.60   270.0  $32.60  $22.80

然后我用以下行提取时间列:

df["time"] = df.itime

df["time"]

0       1000.0
1       1000.0
2       1030.0
3       1100.0
4       1130.0
5       1200.0
6       1230.0
7       1300.0
8       1330.0
.
.
3261    2130.0
3262    2130.0
3263     600.0
3264     630.0
3265     730.0
3266     800.0
3267     830.0
3268    1900.0
3269    1930.0
3270    2000.0

Name: time, Length: 3279, dtype: float64

然后我尝试将time列转换为datetime对象:

df["time"] = pd.to_datetime(df.itime)

产生了以下结果:

df["time"]

0      1970-01-01 00:00:00.000001000
1      1970-01-01 00:00:00.000001000
2      1970-01-01 00:00:00.000001030
3      1970-01-01 00:00:00.000001100

似乎已成功将数据转换为datetime对象。但是,它增加了小时时间到ms,这对我来说很难进行过滤。

我想要获得的最终数据格式是:

1970-01-01 06:00:00

06:00

感谢您的帮助。

3 个答案:

答案 0 :(得分:3)

当您读取excel文件时,将列dtype的{​​{1}}指定为itime

str

然后您将看到一个时间字符串列,如下所示:

df = pd.read_excel("test.xlsx", dtype={'itime':str})

然后指定格式并转换为时间:

df = pd.DataFrame({'itime':['2300', '0100', '0500', '1000']})

答案 1 :(得分:2)

只需添加Chri的答案,如果由于前面没有零而无法转换,请将以下内容应用于数据框。

ByteArrayOutputStream baos = new ByteArrayOutputStream();
    OPCPackage pkg = OPCPackage.open(file);
    XSSFWorkbook xls = new XSSFWorkbook(pkg);
    XSSFSheet worksheet = xls.getSheetAt(0);

基本上是因为原始格式甚至没有前导数字(4位)。例如:945而不是0945。

答案 2 :(得分:0)

尝试

df["time"] = pd.to_datetime(df.itime).dt.strftime('%Y-%m-%d %H:%M:%S')


df["time"] = pd.to_datetime(df.itime).dt.strftime('%H:%M:%S')

对于您想要的第一和第二输出

最好!