【问题标题】:Pandas to csv datetime mismatch while converting to csvPandas 转换为 csv 时与 csv 日期时间不匹配
【发布时间】:2018-12-07 08:17:18
【问题描述】:

我有一个看起来像这样的数据框,时间戳以 UTC 秒为单位

               open     high      low    close    volumeto
time                                                      
1530169200  6112.81  6120.62  6108.65  6111.63  2212255.01
1530170100  6111.63  6119.12  6106.45  6113.59  1572299.36
1530171000  6113.59  6116.44  6104.34  6110.23  2792660.45
1530171900  6110.23  6123.71  6106.49  6123.71  2314140.04
1530172800  6121.33  6133.24  6121.18  6129.52  2037071.96

当我尝试将其写入 csv 时,这就是我得到的,我猜 pandas 假设提供的时间是本地时间并将其偏移 5 小时 30 分钟,但我提供了 UTC 时间

1530149400,6112.81,6120.62,6108.65,6111.63,2212255.01:
1530150300,6111.63,6119.12,6106.45,6113.59,1572299.36:
1530151200,6113.59,6116.44,6104.34,6110.23,2792660.45:
1530152100,6110.23,6123.71,6106.49,6123.71,2314140.04:
1530153000,6121.33,6133.24,6121.18,6129.52,2037071.96:

我的代码如下所示

csv_string = io.StringIO()
df.to_csv(csv_string, line_terminator=':', header=False, date_format='%s')
print(csv_string.getvalue())

我如何告诉 Pandas 我已经提供了 UTC 时间并且不想在转换时抵消它?

【问题讨论】:

    标签: python pandas csv datetime


    【解决方案1】:

    一种方法是首先使用tz_localize() 使时间列可识别时区。在您的情况下,假设您的 DataFrame 称为df

    df.index = df.index.tz_localize(tz='UTC')
    

    现在,索引可以识别时区。但是,我不确定这是否是时间不同的原因。

    编辑 如果索引已经附加了一个 tz,您可以像添加时区一样更改它,但现在使用 tz_convert,如您的错误所示。代码将变为:

    df.index = df.index.tz_convert(tz='UTC')
    

    但是,这也会修改时间。为了用时区 UTC 替换时区,您需要执行以下操作:

    import pytz
    df.index = [t.replace(tzinfo=pytz.utc) for t in df.index]
    

    但是,在您执行此操作之前,最好先检查一下时区,看看这是否对应于 5:30 时差。此外,还要意识到使用date_format='%s' 会忽略时区信息,通常会假定系统的时区。有关更多信息,请参阅以下已接受的答案:

    Python - Setting a datetime in a specific timezone (without UTC conversions)

    顺便说一句,如果我只是将您的 DataFrame 复制粘贴到我的机器上并将其写入 to_csv 它就会按预期工作。

    【讨论】:

    • 感谢您的尝试,TypeError: 已经 tz-aware,使用 tz_convert 进行转换。给我这个错误
    猜你喜欢
    • 1970-01-01
    • 2017-08-29
    • 1970-01-01
    • 1970-01-01
    • 2017-01-30
    • 1970-01-01
    • 1970-01-01
    • 2021-04-09
    • 1970-01-01
    相关资源
    最近更新 更多