futurelj
futurelj

Reputation: 273

datetime64[ns] to Timestamp String in Pandas

I haver a Series:

>>> 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]

And the ser[0] and 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]

The values of ser are:

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]')

The problem is that , for example, the time is '2008-08-06T02:36:48.000000000+0800' and not is '2008-08-05 18:36:48'

I need import the values of ser into Database like this: ['2008-08-05 18:36:48','2008-08-01 14:45:37','2008-09-08 14:03:52']

How can I get the list of timestamp, not the '2008-08-06T02:36:48.000000000+0800'?

Upvotes: 2

Views: 2352

Answers (1)

Jianxun Li
Jianxun Li

Reputation: 24752

One way is to construct pd.DatetimeIndex and call 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)

Or just manipulate on numpy array (set resolution to s instead of ns and then convert to string):

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')    

Upvotes: 2

Related Questions