0

I have a pandas dataframe where the date column contains values such as: 20190709 20190710 20190708

let's call this column: date

I want to convert this to appear as '2019-07-09'

trying some random things, but seem to be way off base. Can anyone help me get the right formula for this? I'm guessing it is pretty simple but I am spending more time guessing than necessary

Here is one thing I've tried recently, not sure what is happening

df['date2'] = datetime.strptime(df['date'].astype(str),"%Y-%m-%d")

getting an error message of "strptime() argument 1 must be str, not Series"

2 Answers 2

1

It's easier than you thought, Pandas has a pretty good auto-parser for dates, so it'll get the format without pre-parsing the string. Working example with a series:

a = ['20190709', '20190710']
a = pd.Series(a)
df['date2'] = pd.to_datetime(a)

In your case, this should do:

df['date2'] = pd.to_datetime(df['date'])
Sign up to request clarification or add additional context in comments.

Comments

1

If you have consistent digits in the date, which it appears like you do, you can slice the string:

>>> s = '20190708'
>>> datestr = '-'.join([s[:4], s[4:6], s[6:] ])
>>> datetime.strptime(datestr,"%Y-%m-%d")
datetime.datetime(2019, 7, 8, 0, 0)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.