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"
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'])
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.