Python 如何将pandas时区感知时间戳转换为UNIX epoche?

Python 如何将pandas时区感知时间戳转换为UNIX epoche?,python,numpy,pandas,epoch,datetime64,Python,Numpy,Pandas,Epoch,Datetime64,我需要将时区感知日期范围(时间戳)转换为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=['value

我需要将时区感知日期范围(时间戳)转换为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值存储时间戳

是否有一种聪明的方法可以在请求的时区中获得“正确”的历元值

使用索引方法
asi8
转换为int64(自epoch以来已在
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数据(以及时区,如果需要)


我同意并通过在UTC中交换时间戳并使用JavaScript转换为本地浏览器时区解决了这个问题。
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])
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])