Reputation: 4345
I have a column in pandas dataframe like this:
>>> print(df['SESSION_DATE'])
0 2008-05-20
1 2013-03-15
2 2014-10-14
3 2006-08-04
4 2006-11-20
Name: SESSION_DATE, dtype: datetime64[ns]
I am trying to create a new column based on this one. But I want the timestamp to show as well. Here is what I tried:
>>> df['NEW_COMPL_DTE'] = pd.to_datetime(df['SESSION_DATE'])
>>> print(df['NEW_COMPL_DTE'])
0 2008-05-20
1 2013-03-15
2 2014-10-14
3 2006-08-04
4 2006-11-20
Name: NEW_COMPL_DTE, dtype: datetime64[ns]
I was hoping the output would include a 00:00:00
after each date. Please advise.
Upvotes: 2
Views: 2110
Reputation: 402523
If no timestamp is included, 00:00:00
is assumed, so pd.to_datetime
does not explicitly display it.
If all you want to do is display it, you may do:
pd.to_datetime(s).dt.strftime('%y-%m-%d %h:%I:%s')
0 2008-05-20 00:00:00
1 2013-03-15 00:00:00
2 2014-10-14 00:00:00
3 2006-08-04 00:00:00
4 2006-11-20 00:00:00
Name: 1, dtype: object
Alternatively, this is simpler, but not as neat. You can use this if your column has strings.
s + ' 00:00:00'
0 2008-05-20 00:00:00
1 2013-03-15 00:00:00
2 2014-10-14 00:00:00
3 2006-08-04 00:00:00
4 2006-11-20 00:00:00
Name: 1, dtype: object
Upvotes: 3
Reputation: 62
You should be able to use this
import numpy as np
import pandas as pd
from datetime import datetime
dates = [datetime(2008, 5, 20), datetime(2013, 3, 15), datetime(2012, 10, 14), datetime(2006, 8, 4), datetime(2006, 11,20)]
index = pd.DatetimeIndex(dates)
for i in index.astype(np.int64):
print(pd.to_datetime(i, unit='ns'))
to get this
2008-05-20 00:00:00
2013-03-15 00:00:00
2012-10-14 00:00:00
2006-08-04 00:00:00
2006-11-20 00:00:00
Upvotes: 0
Reputation: 171
I think you should use strptime. Like:
from datetime import datetime
mywanteddate = datetime.strptime("%s 00:00:00" % (df['SESSION_DATE']), "%Y-%m-%d %H:%M:%S")
print(mywanteddate) # 2008-05-20 00:00:00
Upvotes: 0