Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to convert index from datetime.date to datetime.datetime?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

Thanks

>Solution :

  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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading