How to covnert int64 data into ?day, month and year?

Question:

I have a date feature in the format 20001130 and another 2000-11-30 without any space. How can i write the optimized code that works for both to split the date into day month and year efficiently

Asked By: Mohammed Nadeem

||

Answers:

You can use pandas.to_datetime:

import pandas as pd
pd.to_datetime([20001130, 20001129], format='%Y%m%d')

or with a dataframe.

df = pd.DataFrame({'time': [20001129, 20001130]})
df.time = pd.to_datetime(df.time, format='%Y%m%d')

EDIT
The two date formats should be in one column. In this case, convert all to strings and let pandas.to_datetime interpret the values, as it supports different formats in one column.

df = pd.DataFrame({'time': [20001129, '2000-11-30']})
df.time = pd.to_datetime(df.time.astype(str))
time
0 2000-11-29
1 2000-11-30
Answered By: Andrew
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.