- How do I change the date formats to YYYY/MM/DD for each date column in the data frame, illustrated, using python?
- How do I create a new column within the data frame called, "time difference between dates" by subtracting the "Applied Date" column from the "Hired Date" column.
Asked
Active
Viewed 46 times
1

Jed
- 331
- 2
- 11
-
how the date difference should look like? share the expected output – Naveed Oct 26 '22 at 16:11
-
did the answer helped? – Naveed Oct 26 '22 at 21:35
-
@Naveed Hey, so when I apply the code in python, the dates aren't changed into the format that is desired. I am wondering whether this is because the date is originally seen as an "object" in python and not a "string"? Or should this not make a difference? – Jed Oct 27 '22 at 08:15
-
if you share the data as a code (preferably) or as a text. I'll be able to share the result on your data. Please refer to the StackOverflow guidelines in sharing reproducible example – Naveed Oct 27 '22 at 13:15
-
@Naveed No worries, there was an error on my side. I replicated your code in Python and everything works now. Thank you! Just had one last question. You converted the format of the two date columns in two steps. Is there a way to convert the format of the date columns in one go, rather than having one line for every date column I had. i.e. if I had 5 date columns, would I have to replicate the code 5 times? – Jed Oct 27 '22 at 14:27
-
updated the solution to convert multiple dates in a single statement – Naveed Oct 27 '22 at 14:43
1 Answers
2
if you share the data as a code (preferably) or as a text. I'll be able to share the result on your data. Please refer to the StackOverflow guidelines in shareing reproducible example
# for converting to the YYYY/MM/DD Format
df['date']=pd.to_datetime(df['date']).dt.strftime('%Y/%m/%d')
df['date2']=pd.to_datetime(df['date2']).dt.strftime('%Y/%m/%d')
# for calculating the difference b/w two dates
pd.to_datetime(df['date']) - pd.to_datetime(df['date2'])
alternately,
# list of the date columns to convert
dates= ['date','date2']
# apply conversion to each of dates in the list
df[dates] = df[dates].apply(lambda x: pd.to_datetime(x).dt.strftime('%Y/%m/%d'))
# for calculating the difference b/w two dates
pd.to_datetime(df['date']) - pd.to_datetime(df['date2'])

Naveed
- 11,495
- 2
- 14
- 21