我有以下Dataframe
df1:
col1 col2 timestamp
0 4 1512712800000
1 6 1512712800000
2 4 1518510600000
3 8 1512712800000
4 9 1518510600000
我想像这样转换时间戳
datetime.fromtimestamp(int("1518485400000")/1000)
>>>>2018-02-13 02:30:00
并将其另存为数据框中的新列
所以看起来应该是这样的
df1:
col1 col2 timestamp Date
0 4 1512712800000 2018-02-13 02:30:00
1 6 1512712800000 2018-02-13 04:30:00
2 4 1518510600000 2018-02-13 01:35:00
3 8 1512712800000 2018-02-13 08:30:00
4 9 1518510600000 2018-02-13 09:30:00
然后我试着以这种方式做到这一点
df1['Date'] = (datetime.fromtimestamp(int(df1.timestamp)/1000))
但是我收到编译错误。有什么问题,我该如何解决?
谢谢!
答案 0 :(得分:3)
尝试这样的事情:
import pandas as pd
import datetime
df = pd.DataFrame({'col': [1,2], 'timestamp': ['1512712800000','1512713800000']})
print df
# col timestamp
# 0 1 1512712800000
# 1 2 1512713800000
convDate = lambda x: datetime.datetime.fromtimestamp(int(x)/1000)
df['date'] = df['timestamp'].apply(convDate)
print df
# col timestamp date
# 0 1 1512712800000 2017-12-08 06:00:00
# 1 2 1512713800000 2017-12-08 06:16:40
答案 1 :(得分:0)
这对你有用吗?
df1["Date"] = [datetime.fromtimestamp(int(x)/1000) for x in df1["timestamp"]]
我用以重新创建示例的完整代码:
import pandas as pd
from datetime import datetime
df1 = pd.DataFrame({"col1":[0,1,2,3,4],
"col2":[4,6,4,8,9],
"timestamp":["1512712800000","1512712800000","1518510600000","1512712800000","1518510600000"]})
df1["Date"] = [datetime.fromtimestamp(int(x)/1000) for x in df1["timestamp"]]
print (df1)
输出是这样的:
col1 col2 timestamp Date
0 0 4 1512712800000 2017-12-08 07:00:00
1 1 6 1512712800000 2017-12-08 07:00:00
2 2 4 1518510600000 2018-02-13 09:30:00
3 3 8 1512712800000 2017-12-08 07:00:00
4 4 9 1518510600000 2018-02-13 09:30:00