我正在尝试执行循环以将数据帧中的时间戳列转换为ISO 8601格式。然而,它以奇怪的小时:分钟:秒继续回到1970年的数据。但是,如果我只选择一个时间戳并运行中间代码“tz = ... iso.format())”,它就可以正常工作。
df= pd.read_csv('file.csv')
for i in range(len(df)):
timestamp=df.loc[i,'timestamp']
# print(timestamp)
#forloops to print ISO 8601 format
res=[]
def ISOformat():
tz = pytz.timezone('America/Los_Angeles')
print(datetime.fromtimestamp(i, tz).isoformat())
for i in range(len(df)):
res.append(ISOformat())
#make a dataframe of the ISO 8601
iso_8601_test= pd.DataFrame({'ISO_8601_time':res})
我喜欢我的输出是这样的: 2011-12-31T16:05:00-08:00 不是1970年代的时间。
我的时间戳示例:
timestamp
1325376300
1325376600
1325376900
1325377200
1325377500
1325377800
1325378100
1325378400
1325378700
1325379000
1325379300
1325379600
1325379900
答案 0 :(得分:0)
我认为您可以使用Timestamp
函数以您想要的方式创建列。您可以使用apply
:
res = df['timestamp'].apply(lambda time: pd.Timestamp(time,
tz='America/Los_Angeles',unit='s').isoformat())
然后按照您的方式创建数据框:
iso_8601_test= pd.DataFrame({'ISO_8601_time':res})
您的输出就像(输入数据中的前两个数字):
ISO_8601_time
0 2011-12-31T16:05:00-08:00
1 2011-12-31T16:10:00-08:00