Suppose I have a Dataframe as:
df = {'date':['20170101', '20170102', '20170103', '20170104']}
I want to convert '20170101'
to '2017-01-01 00:00:00'
How can I achieve it?
Suppose I have a Dataframe as:
df = {'date':['20170101', '20170102', '20170103', '20170104']}
I want to convert '20170101'
to '2017-01-01 00:00:00'
How can I achieve it?
You could convert your date time string to datetime
object. And then get whatever format you want:
from datetime import datetime
datetime.strptime("20170103", "%Y%m%d").strftime("%Y-%m-%d %H:%M:%S")
Output:
"2017-01-03 00:00:00"
If you have a pandas.DataFrame
you can do that with:
pd.to_datetime(df['date'], format='%Y%m%d')
df = pd.DataFrame({'date':['20170101', '20170102', '20170103', '20170104']})
df['date2'] = df['date'].apply(lambda d: dt.datetime.strptime(d, '%Y%m%d'))
df['date3'] = pd.to_datetime(df['date'], format='%Y%m%d')
print(df)
date date2 date3
0 20170101 2017-01-01 2017-01-01
1 20170102 2017-01-02 2017-01-02
2 20170103 2017-01-03 2017-01-03
3 20170104 2017-01-04 2017-01-04
If you know how the string is built (i.e. YYYYMMDD
) you can simply use this:
def f(s):
return '{}-{}-{} 00:00:00'.format(s[:4],s[4:6],s[6:])
s = '20170101'
f(s)
Out[7]: '2017-01-01 00:00:00'