2021年3月31日星期三

Dates to timestamp in pandas

There are abundant examples of how to convert different timestamp formats to datetime objects, but almost none for the other way around.

My goal is simply to convert datetime dates to timestamps (i.e. to include 00:00:00 for hours, minutes and seconds), which I assume must be done by first adding hours, minutes, and seconds to the datetime object which can then be converted to string. My dataframe looks like this:

data.head()  start_date  end_date  0   2013-01-10  2013-01-10  1   2013-01-26  2013-01-26  2   2013-01-26  2013-01-26  3   2013-01-26  2013-01-26  4   2013-02-13  2013-02-13      data.dtypes  start_date    object  end_date      object  dtype: object  

I have tried combining pandas.Timestamp() with astype(str) but this does not return the result that is needed.

#this returns the right timestamp  pd.Timestamp(data['start_date'][0])  Timestamp('2013-01-10 00:00:00')    #H:M:S disappears   data['start_date'] = data.apply(lambda row : pd.Timestamp(row['start_date']), axis = 1)  data['start_date'].astype(str)  0      2013-01-10  1      2013-01-26  2      2013-01-26  3      2013-01-26  4      2013-02-13  

What is the correct method in pandas to convert from date to strings that look like '2013-01-10 00:00:00' (without converting date to string then adding + '00:00:00') ? There should be something simpler

https://stackoverflow.com/questions/66898172/dates-to-timestamp-in-pandas April 01, 2021 at 11:47AM

没有评论:

发表评论