3

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?

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
xxyao
  • 529
  • 1
  • 7
  • 16
  • 1
    Flow this link and you will get answer [click here](https://stackoverflow.com/questions/46834732/convert-pandas-datetime-column-yyyy-mm-dd-to-yyymmdd) – Robiul Islam Jan 30 '18 at 08:15

3 Answers3

4

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"
Kevin
  • 483
  • 3
  • 12
3

If you have a pandas.DataFrame you can do that with:

Code:

pd.to_datetime(df['date'], format='%Y%m%d')

Test Code:

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)

Results:

       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
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
0

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'
CIsForCookies
  • 12,097
  • 11
  • 59
  • 124