代码之家  ›  专栏  ›  技术社区  ›  proximacentauri

熊猫转换mongodb bson。tz\u util。固定偏移到标准日期

  •  0
  • proximacentauri  · 技术社区  · 7 年前

    我试图使用从mongodb文档中的数据创建的熊猫数据帧来计算从历元秒的偏移量。

    数据布局和操作示例如下所示(此代码正常工作)

    data = {'ds': ['2018-01-13 18:47:05.069722+00:00', '2018-01-14 18:47:05.119994+00:00', '2018-01-15 18:47:05.178768+00:00'], 
            'y': [38, 20, 26]}
    df = pd.DataFrame(data, columns = ['ds', 'y']) 
    df['ds'] = pd.to_datetime(df['ds'])
    t = np.array(
                        (df['ds'] - pd.datetime(1970, 1, 1))
                        .dt.total_seconds()
                        .astype(np.float)
                    ) / (3600 * 24.)
    

    但请注意,上面代码中ds列的数据类型为

    datetime64[ns]
    

    实际熊猫数据中日期列的数据类型为

    datetime64[ns, <bson.tz_util.FixedOffset objec...
    

    我能够解决这个问题的唯一方法是将其转换为字符串,然后返回到最新版本:

    dates = df['ds'].apply(lambda x: x.strftime('%Y-%m-%d %H:%M:%S'))
    df['ds'] = pd.to_datetime(dates)
    

    有没有更好的方法来转换

    datetime64[ns, <bson.tz_util.FixedOffset object  
    

    转换为Pandas中的datetime64[ns]列类型?

    1 回复  |  直到 7 年前
        1
  •  1
  •   teemoleen    7 年前

    这对我有用。

    import pandas as pd
    
    # have to convert the series to date index
    dsIndex = pd.Index(df['ds'])
    
    # strip off the TZ info (assume it was <bson.tz_util.FixedOffset objec...)
    dsIndex = dsIndex.tz_localize(tz=None)
    
    # Reassign it to UTC
    dsUTC = dsIndex.tz_localize(tz='UTC')
    
    推荐文章