【问题标题】:How to convert pandas timezone aware timestamps to UNIX epoche?如何将熊猫时区感知时间戳转换为 UNIX 纪元?
【发布时间】:2014-05-19 21:48:20
【问题描述】:

我需要将时区感知 date_range (TimeStamps) 转换为 UNIX 纪元值,以便在外部 Javascript 库中使用。

我的做法是:

# Create localized test data for one day
rng = pd.date_range('1.1.2014', freq='H', periods=24, tz="Europe/Berlin")
val = np.random.randn(24)
df = pd.DataFrame(data=val, index=rng, columns=['values'])

# Reset index as df column
df = df.reset_index()

# Convert the index column to the desired UNIX epoch format
df['index'] = df['index'].apply(lambda x: x.value // 10**6 )

df['index'] 包含预期的 UNIX 纪元值,但它们存储在 UTC(!) 中。

我想这是因为 pandas 将时间戳存储在 numpy UTC datetime64 值中。

有没有一种聪明的方法可以在请求的时区中获取“正确”的纪元值?

This proposal doesn't work with DST

【问题讨论】:

    标签: python numpy pandas epoch datetime64


    【解决方案1】:
    In [17]: df
    Out[17]: 
                                 values
    2014-01-01 00:00:00+01:00  1.027799
    2014-01-01 01:00:00+01:00  1.579586
    2014-01-01 02:00:00+01:00  0.202947
    2014-01-01 03:00:00+01:00 -0.214921
    2014-01-01 04:00:00+01:00  0.021499
    2014-01-01 05:00:00+01:00 -1.368302
    2014-01-01 06:00:00+01:00 -0.261738
    
    2014-01-01 22:00:00+01:00  0.808506
    2014-01-01 23:00:00+01:00  0.459895
    
    [24 rows x 1 columns]
    

    使用索引方法asi8 转换为int64(自纪元以来已经在ns 中) 这些是 UTC 时间!

    In [18]: df.index.asi8//10**6
    Out[18]: 
    array([1388530800000, 1388534400000, 1388538000000, 1388541600000,
           1388545200000, 1388548800000, 1388552400000, 1388556000000,
           1388559600000, 1388563200000, 1388566800000, 1388570400000,
           1388574000000, 1388577600000, 1388581200000, 1388584800000,
           1388588400000, 1388592000000, 1388595600000, 1388599200000,
           1388602800000, 1388606400000, 1388610000000, 1388613600000])
    

    这些是自纪元以来的本地时区。请注意,这通常不是公共方法,我总是会交换 UTC 数据(如果需要,还可以交换时区)。

    In [7]: df.index._local_timestamps()//10**6
    Out[7]: 
    array([1388534400000, 1388538000000, 1388541600000, 1388545200000,
           1388548800000, 1388552400000, 1388556000000, 1388559600000,
           1388563200000, 1388566800000, 1388570400000, 1388574000000,
           1388577600000, 1388581200000, 1388584800000, 1388588400000,
           1388592000000, 1388595600000, 1388599200000, 1388602800000,
           1388606400000, 1388610000000, 1388613600000, 1388617200000])
    

    【讨论】:

    • 我同意并通过交换 UTC 时间戳并使用 JavaScript 转换为本地浏览器时区来解决它。
    猜你喜欢
    • 2021-05-02
    • 2021-07-09
    • 2018-08-03
    • 2023-03-27
    • 2013-05-13
    • 1970-01-01
    • 1970-01-01
    • 2013-01-08
    相关资源
    最近更新 更多