首页 > 解决方案 > 如何以毫秒为单位将 unix 时间戳转换为日期时间 python 3

问题描述

我有一个带有 unix(纪元)时间的大型数据集,我需要以毫秒为单位将其转换为日期时间。我的代码应该完成这项工作,因为我指定返回毫秒,但不知何故它只返回几秒钟。需要改变什么?

import pandas as pd

# reading in the excel file timestamps.xlsx
# this file contains a column 'epoch' with the unix epoch timestamps
df = pd.read_excel('epoch_time.xlsx')

# translate epochs into human readable and write into newly created column
# timestamps are in ms, hence the unit
df['time'] = pd.to_datetime(df['epoch'], unit='ms')

# remove epoch row
df = df.drop('epoch', axis=1)

# write to excel file 'new_timestamps.xlsx'
# index=False prevents pandas to add the indices as a new column
df.to_excel('new_timestamps.xlsx', index=False)

标签: pythonpython-3.xpandasdatetime

解决方案


我想这就是你要找的东西:

pd.to_datetime(1582200012345, unit='ms').to_datetime64()

输出:

numpy.datetime64('2020-02-20T12:00:12.345000000')

或用于列:

df['time'] = pd.to_datetime(df['time'], unit='ms').apply(lambda x: x.to_datetime64())

例子:

df=pd.DataFrame([1582200012345,1582200012346])
df['time'] = pd.to_datetime(df[0], unit='ms').apply(lambda x: x.to_datetime64())
df
               0                    time
0  1582200012345 2020-02-20 12:00:12.345
1  1582200012345 2020-02-20 12:00:12.346

推荐阅读