在Python中将时间戳数据转换为日期时间

时间:2020-05-29 00:38:22

标签: python pandas csv

我有一个带有包含时间戳记的列的DataFrame,我想在Python中将该列转换为日期时间,并使用包含日期和时间的列保存文件。这是代码:


    import pandas as pd
    df = pd.DataFrame({
        "time": [1465585763000, 1465586363000, 1465586963000, 
                  1465587563000, 1465588163000]})
    df

2 个答案:

答案 0 :(得分:1)

这也可以工作

import pandas as pd
from datetime import datetime as dt
d = {'time': [1465585763000, 1465586363000, 1465586963000,
              1465587563000, 1465588163000]}


print(d['time'])
new = [dt.fromtimestamp(x/1000).strftime('%Y-%m-%d %H:%M:%S') for x in d['time']]
pd.to_datetime(new)


答案 1 :(得分:0)

这可能有效

from datetime import datetime as dt
import pandas as pd

times = [
    1465585763000, 
    1465586363000, 
    1465586963000, 
    1465587563000, 
    1465588163000]

start_ts = dt.timestamp(dt(1970, 1, 1))
dates = [dt.fromtimestamp(time / 1000 + start_ts) for time in times]
pd.to_datetime(dates)