datetime64 [ns]到Pandas中的时间戳字符串

时间:2015-07-24 14:22:08

标签: python pandas

我有一个系列:

>>> ser = pd.Series(['2008-08-05 18:36:48','2008-08-01 14:45:37','2008-09-08 14:03:52'],index=[0,1,2],dtype='datetime64[ns]')

>>> ser

0   2008-08-05 18:36:48

1   2008-08-01 14:45:37

2   2008-09-08 14:03:52

dtype: datetime64[ns]

ser [0]和ser [0:1]

>>> ser[0]
Timestamp('2008-08-05 18:36:48')
>>>ser[0:2]
0   2008-08-05 18:36:48
1   2008-08-01 14:45:37
dtype: datetime64[ns]

ser的值是:

ser.values
array(['2008-08-06T02:36:48.000000000+0800',
   '2008-08-01T22:45:37.000000000+0800',
   '2008-09-08T22:03:52.000000000+0800'], dtype='datetime64[ns]')

问题是,例如,时间是' 2008-08-06T02:36:48.000000000 + 0800' 而不是' 2008 -08-05 18:36:48'

我需要将ser的值导入到数据库中,如下所示: [' 2008-08-05 18:36:48',' 2008-08-01 14:45:37',' 2008-09-08 14 :03:52']

如何获取时间戳列表,而不是' 2008-08-06T02:36:48.000000000 + 0800'?

1 个答案:

答案 0 :(得分:1)

一种方法是构建pd.DatetimeIndex并调用to_native_types()

pd.DatetimeIndex(ser).to_native_types()

array(['2008-08-05 18:36:48', '2008-08-01 14:45:37', '2008-09-08 14:03:52'], dtype=object)

或者只是操作numpy数组(将分辨率设置为s而不是ns,然后转换为字符串):

ser.values.astype('<M8[s]').astype(str)

array(['2008-08-05T18:36:48Z', '2008-08-01T14:45:37Z', '2008-09-08T14:03:52Z'], 
      dtype='<U38')