簡體   English   中英

如何將pandas timezone aware timestamps轉換為UNIX epoche?

[英]How to convert pandas timezone aware timestamps to UNIX epoche?

我需要將時區感知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值中。

有沒有一種聰明的方法可以在要求的時區內獲得“正確”的紀元價值?

此提案不適用於DST

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])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM