【问题标题】:Pandas data frame - to_json() to_csv() don't act the same for dates in iso formatPandas 数据框 - to_json() to_csv() 对于 iso 格式的日期的行为不同
【发布时间】:2019-04-28 21:12:09
【问题描述】:

我从我的 API 获取 iso 格式的日期。

当我在做的时候:

df = DataFrame(results)
df.to_csv(path_or_buf=file_name, index=False, encoding='utf-8',
          compression='gzip',
          quoting=QUOTE_NONNUMERIC)

我查看了我看到的 CSV,例如:

lastDeliveryDate
2018-11-21 16:25:53.990000-05:00

然而,

当我这样做时:

df = DataFrame(results)
df.to_json(path_or_buf=file_name, orient="records",compression='gzip', lines=True)

我看到(其他记录):

"lastDeliveryDate":1543258826689

这是个问题。

当我将数据从 CSV 加载到 Google BigQuery 时,一切都很好。日期解析正确。

但是当我将加载更改为 Json 时。它没有正确解析日期。

我以这种格式查看日期:

50866-01-09 23:46:40 UTC

这是因为to_json()to_csv()iso_format 中的日期产生不同的结果

我该如何解决这个问题?我必须编辑数据框并将所有日期列转换为常规 UTC 吗?我怎样才能做到这一点?为什么需要 to_json() 而不是 for to_csv()

正如How do I translate an ISO 8601 datetime string into a Python datetime object? 解释的那样尝试做:

df["lastDeliveryDate"] = dateutil.parser.parse(df["lastDeliveryDate"])  

但它给出了:

TypeError: Parser 必须是字符串或字符流,而不是 Series

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    来自Pandas documentation on to_json()

    date_format{无,'epoch','iso'}
    日期转换的类型。 ‘epoch’ = 纪元毫秒,‘iso’ = ISO8601。默认值取决于方向。对于orient='table',默认为“iso”。对于所有其他方向,默认值为“epoch”。

    因此,对于orient="records",您必须设置date_format="iso" 以获得稍后可以理解的日期时间格式:

    df.to_json(path_or_buf=file_name, orient="records", date_format="iso", 
               compression='gzip', lines=True)
    

    【讨论】:

      【解决方案2】:

      基本上dateutil.parser.parse() 期望一个字符串作为参数,但您传递了整个列。尝试使用 lambda 函数:

      df["lastDeliveryDate"] = df["lastDeliveryDate"].apply( lambda row: dateutil.parser.parse(row))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-11-29
        • 1970-01-01
        • 1970-01-01
        • 2013-09-08
        • 2016-04-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多