Python Pandas:将日期字符串转换为自纪元和日期字符串以来的毫秒数?

时间:2016-12-21 16:13:20

标签: python pandas

尝试使用以下代码将日期字符串转换为自纪元以来的毫秒数和返回日期字符串:

def date_to_millis(s) :                                                                                         
    t = pd.Timestamp(s)                                                                                         
    return time.mktime(t.timetuple())                                                                           

s = "2013-01-14 00:00:00"                                                                                       
mls = date_to_millis(s)                                                                                         
dateStr = pd.to_datetime(mls, unit='ms')                                                                        
print(s, " mls = ", mls, "  date = " , dateStr)

我得到以下字符串不匹配的结果:

('2013-01-14 00:00:00', ' mls = ', 1358107200.0, '  date = ', Timestamp('1970-01-16 17:15:07.200000')) 

此外,在IPython交互式会话中重新运行此代码时,我收到错误:

AttributeError                            Traceback (most recent call last)                                     
<ipython-input-9-6a819827f8f2> in <module>()                                                                    
----> 1 time.mktime(t.timetuple())                                                                              

AttributeError: 'Timestamp' object has no attribute 'mktime'                                                    

可能出错的是什么?如何将日期字符串转换为epoch和back to date字符串后的毫秒数?

1 个答案:

答案 0 :(得分:1)

你的date_to_millis函数转换为秒而不是毫秒。

您需要使用“to_datetime64”而不是时间元组。

# %%
import pandas as pd
import time
def date_to_millis(s) :                                                                                         
    return pd.to_datetime(s).to_datetime64()                                                                                  


s = "2013-01-14 00:00:00"                                                                                       
mls = date_to_millis(s)                                                                                         
dateStr = pd.to_datetime(mls, unit='ms')                                                                        
print(s, " mls = ", mls, "  date = " , dateStr)
# %%
2013-01-14 00:00:00  mls =  2013-01-14T00:00:00.000000000   date =  2013-01-14 00:00:00

print(float(mls))
1.3581216e+18