Home > Blockchain >  how to convert index from datetime.date to datetime.datetime?
how to convert index from datetime.date to datetime.datetime?

Time:06-16

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()?

CodePudding user response:

  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
  • Related