您好,我正在尝试导入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等
那么这里的陷阱在哪里
那么:
您提供了一个精确的格式,使您能够保留感兴趣的时区。有关日期时间格式here的信函的详细信息
编辑: 如果您想处理夏季/冬季时间,可以将
+01
替换为+%f
相关问题 更多 >
编程相关推荐