Convert pandas DateTimeIndex to Unix Time?

后端 未结 6 1636
故里飘歌
故里飘歌 2020-11-28 06:22

What is the idiomatic way of converting a pandas DateTimeIndex to (an iterable of) Unix Time? This is probably not the way to go:

[time.mktime(t.timetuple()         


        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-28 07:08

    To address the case of NaT, which above solutions will convert to large negative ints, in pandas>=0.24 a possible solution would be:

    def datetime_to_epoch(ser):
        """Don't convert NaT to large negative values."""
        if ser.hasnans:
            res = ser.dropna().astype('int64').astype('Int64').reindex(index=ser.index)
        else:
            res = ser.astype('int64')
    
        return res // 10**9
    

    In the case of missing values this will return the nullable int type 'Int64' (ExtensionType pd.Int64Dtype):

    In [5]: dt = pd.to_datetime(pd.Series(["2019-08-21", "2018-07-28", np.nan]))                                                                                                                                                                                                    
    In [6]: datetime_to_epoch(dt)                                                                                                                                                                                                                                                   
    Out[6]: 
    0    1566345600
    1    1532736000
    2           NaN
    dtype: Int64
    

    Otherwise a regular int64:

    In [7]: datetime_to_epoch(dt[:2])                                                                                                                                                                                                                                               
    Out[7]: 
    0    1566345600
    1    1532736000
    dtype: int64
    

提交回复
热议问题