无法将索引正确转换为datetime

2024-09-30 20:21:24 发布

您现在位置:Python中文网/ 问答频道 /正文

您好,我正在尝试导入csv文件并将索引设置为datetime obj。这是csv的示例:

date,wind_force,wind_dir,cloud_cover,temp
2019-01-01 04:00:00+01:00,13.9,234.0,100.0,3.8
2019-01-01 05:00:00+01:00,14.333333,239.33333,100.0,4.5333333

我导入文件并尝试直接在索引上使用pd.to_datetime

dfw = pd.read_csv(r'C:\Path\weather.csv', index_col = 'date')
dfw.index = pd.to_datetime(dfw.index)

然后dfw.index返回:

Index([2019-01-01 04:00:00+01:00, 2019-01-01 05:00:00+01:00,
      ......
       2020-01-01 00:00:00+01:00, 2020-01-01 01:00:00+01:00],
      dtype='object', name='date', length=8750)

如果我尝试dfw.index.hour,我会得到一个错误:

AttributeError: 'Index' object has no attribute 'hour'

当我在将索引更改为datetime时使用utc = True时,它会正确地转换它:

dfw.index = pd.to_datetime(dfw.index, utc = True)

但它返回UTC的日期时间,我希望他们停留在以前的时区

DatetimeIndex(['2019-01-01 03:00:00+00:00', '2019-01-01 04:00:00+00:00',
              ...
               '2019-12-31 23:00:00+00:00', '2020-01-01 00:00:00+00:00'],
              dtype='datetime64[ns, UTC]', name='date', length=8750, freq=None)

另一个奇怪的是,当我尝试按其编号调用index时,如dfw.index[33],它返回:

datetime.datetime(2019, 1, 2, 13, 0, tzinfo=tzoffset(None, 3600))

然后我可以调用dfw.index[33].hours等

那么这里的陷阱在哪里


Tags: 文件csvtonamedatetimedateindexobject
1条回答
网友
1楼 · 发布于 2024-09-30 20:21:24

那么:

dfw.index = pd.to_datetime(dfw.index, format='%Y-%m-%d %H:%M:%S+01:00')

您提供了一个精确的格式,使您能够保留感兴趣的时区。有关日期时间格式here的信函的详细信息

编辑: 如果您想处理夏季/冬季时间,可以将+01替换为+%f

dfw.index = pd.to_datetime(dfw.index, format='%Y-%m-%d %H:%M:%S+%f:00')
dfw.index[0].hour # returns 4

相关问题 更多 >