0

I have a Pandas dataframe with a column which contains strings of the form yyyymmdd.

I would like to create a new column with this date format: yyyy-mm-dd

I tried severals operations as: df['Timestamp'] = df['stringdate'].apply(lambda x:datetime.strptime(x, '%Y-%m-%d')) but it does't work: all my data are 1970-01-01

Perhaps use pd.str.extract of pd.str.split but i'm lost.

Thanks a lot Thierry

mpaepper
  • 3,952
  • 3
  • 21
  • 28
Theo75
  • 477
  • 4
  • 14
  • Does this answer your question? [Convert Pandas Column to DateTime](https://stackoverflow.com/questions/26763344/convert-pandas-column-to-datetime) – deadvoid Jan 15 '20 at 20:11

2 Answers2

0

Your problem is the format key I suspect. It states the format in which the string is, not in which you want it to be in the end. You should use

datetime.datetime.strptime(x, '%Y%m%d')

If you want to have it as a new string in the format yyy-mm-dd you then have to apply strftime:

datetime.datetime.strptime(x, '%Y%m%d').strftime('%Y-%m-%d')
LeoE
  • 2,054
  • 1
  • 11
  • 29
  • I got error: time data '19810501' does not match format '%Y-%m-%d' . I think i have to extract 4 first characters for year, 2 characters for month ...etc ? – Theo75 Jan 16 '20 at 10:15
0

You can use the method pd.to_datetime(Series): https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html

Here is an example:

test = pd.DataFrame(['20200114', '20191223'])
pd.to_datetime(test[0])

Outputs:

0   2020-01-14
1   2019-12-23
Name: 0, dtype: datetime64[ns]
mpaepper
  • 3,952
  • 3
  • 21
  • 28
  • Thanks but can you give me the exact instruction please with a panda dataframe and apply function? Somethinks like df['Timestamp'] = df['date'].apply(lambda x: datetime.datetime.strptime(x, '%Y-%m-%d')) Thanks a lot – Theo75 Jan 16 '20 at 10:20