【问题标题】:Replacing Pandas Timestamp with datetime module用 datetime 模块替换 Pandas 时间戳
【发布时间】:2018-03-04 06:04:48
【问题描述】:

我正在开发一个函数,它将数据集(CSV 文件,加载有 Pandas)的时间戳从本地时间转换为 UTC。为此,我想使用 datetime 模块,因为我在其他函数和脚本中使用它,这些函数和脚本不一定要使用 Pandas 加载数据集。

例如,数据集如下所示:

dtg(local)  temperature  wind speed
2017092003     17.3          7.8
2017092004     17.5          12.4
2017092005     17.6          9.2

其中 dtg 是 pandas 数据帧索引 (yyyymmddHH)。有问题的位置是 UTC+1 并且有夏季夏令时,所以时间应该低 2 小时。我使用了一个函数,该函数利用 datetime 模块来纠正这个时间差(这部分函数工作得很好)。此函数返回日期时间对象列表 (new_index)。我希望将此列表分配为 Dataframe 索引,如下所示:

new_index = times_to_utc(df.index_tolist())
df.set_index([new_index], inplace=True)

但是当我稍后检查数据类型时,会给出:

in[1]: print(new_index[3], type(new_index[3])
out[1]: 2017-09-20 03:00:00 <class 'datetime.datetime'>

in[2]: print(df.index[3], type(df.index[3])
out[2]: 2017-09-20 03:00:00 <class 'pandas._libs.tslib.Timestamp'>

为什么 Pandas 会自动将其转换为 Pandas 时间戳?这真的很不方便,因为其他函数依赖于作为日期时间对象的输入。我可以将索引的日期类型更改为日期时间吗?日期时间?

【问题讨论】:

标签: python pandas datetime


【解决方案1】:

我刚刚通过一些测试发现可以将 pandas 时间戳与 datetime 对象进行比较:

in[0]: import pandas as pd
  ...: from datetime import datetime
  ...: df = pd.DataFrame(index=["2017 09 25 12"], columns=["column"])
  ...: df.index = [datetime.strptime(t, "%Y %m %d %H") for t in df.index]
  ...: print(df.index[0], type(df.index[0]))
  ...: print(df.index[0] == datetime(2017, 9, 25, 12))
  ...: print(isinstance(df.index[0], datetime))

out[0]: 2017-09-25 12:00:00 <class 'pandas._libs.tslib.Timestamp'>
   ...: True
   ...: True

意思是我认为我遇到的问题根本就不是问题......

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-24
    相关资源
    最近更新 更多