2017-03-07 69 views
1

一個在我的數據框列的是D型細胞datetime64的格式 - 2011-01-01 00:00:00如何將一個Series對象傳遞給time.mktime?

'%Y-%m-%dT%H:%M:%S' 

現在,我要列在一個新的DF複製,和值轉換爲UTC時間戳。我曾嘗試以下方法:

from pytz import utc, timezone 
from datetime import datetime 
from time import mktime 

input_dt = pd.to_datetime(df["BaseDateTime"]) 
input_dt 

mktime(timezone('US/Eastern').localize(input_dt).utctimetuple()) 
#OR 
mktime(utc.localize(input_dt).utctimetuple()) 

執行最後兩個語句之後,它會引發以下錯誤:

AttributeError: 'Series' object has no attribute 'tzinfo' 

什麼其他的方法,我應該用得到的該BaseDateTime山坳UTC時間戳數據框?

+0

也許需要'DF [ 「BaseDateTime」] dt.tz_localize (「UT C')',勾選[docs](http://pandas.pydata.org/pandas-docs/stable/timeseries.html#working-with-time-zones) – jezrael

回答

0

datetime值轉換爲紀元值的一種好方法是通過從要轉換的日期中減去曆元時間來創建datetime.timedelta。該功能可以應用於pandas.Seriespandas.DataFrame的列。

代碼:

import pandas as pd 
import datetime as dt 
from pytz import timezone 

def convert_naive_dt_to_utc_epoch(naive_dt, tz_info): 
    # assign proper timezone to datetime 
    aware = tz_info.localize(naive_dt).astimezone(timezone('UTC')) 

    # get a datetime that is equal to epoch in UTC 
    utc_at_epoch = timezone('UTC').localize(dt.datetime(1970, 1, 1)) 

    # return the number of seconds since epoch 
    return (aware - utc_at_epoch).total_seconds() 

測試代碼:

data = [np.datetime64(x) for x in 
     "2016-10-18T13:44:59 2016-02-18T13:59:59".split()] 
series = pd.Series(data=data, name='Date') 

# apply the conversion function to series to create epoch series 
epoch_series = series.apply(
    lambda x: convert_naive_dt_to_utc_epoch(x, timezone('US/Eastern'))) 

print(epoch_series) 

結果:

0 1.476813e+09 
1 1.455822e+09 
Name: Date, dtype: float64 
相關問題