0

I am really confused by time format in pandas.

Here is my dataframe and its index

df.index
Index([2021-10-01, 2021-10-02, 2021-10-03, 2021-10-04, 2021-10-05, 2021-10-06,
       2021-10-07, 2021-10-08, 2021-10-09, 2021-10-10,
       ...
       2022-04-05, 2022-04-06, 2022-04-07, 2022-04-08, 2022-04-09, 2022-04-10,
       2022-04-11, 2022-04-12, 2022-04-13, 2022-04-14],
      dtype='object', length=196)

the individual element of index is type of datetime.date

type(df.index[0])
datetime.date

Now how can I convert whole index into datetime.datetime() instead of datetime.date()?

1 Answer 1

1
  1. datetime.combine
from datetime import datetime
df = pd.DataFrame(index=[datetime.now().date() for _ in range(10)])
print(type(df.index[0]))  # <class 'datetime.date'>
df.index = [datetime.combine(x, datetime.min.time()) for x in df.index]
print(type(df.index[0]))  # <class 'pandas._libs.tslibs.timestamps.Timestamp'> 
print(type(df.index.values[0]))  # numpy.datetime64

  1. datetime.fromisoformat
df = pd.DataFrame(index=[datetime.now().date() for _ in range(10)])
print(type(df.index[0]))  # <class 'datetime.date'>
df.index = [datetime.fromisoformat(x.isoformat()) for x in df.index]
print(type(df.index[0]))  # <class 'pandas._libs.tslibs.timestamps.Timestamp'> 
print(type(df.index.values[0]))  # numpy.datetime64
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Sir, you saved my day. basically i have to use list comprehension to convert each element of index into datetime using iehter isoformat() or combine(). Thank you,

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.