Python 循环将时间戳转换为 ISO 8601 恢复为 1970

Python convert Timestamp to ISO 8601 revert to 1970 in loops

我正在尝试循环将数据帧中的一列时间戳转换为 ISO 8601 格式。然而,它一直回到 1970 年的数据,奇怪 hour:minute:second。但是如果我只选择一个时间戳和 运行 中间代码 "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

我认为您可以使用 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