Search code examples
pythonnumpydatetime-format

Convert datetime64 data to datetime in python


I downloaded a dataset with time data in datetime64 type, I need it in a format where each date value is separated into year, month and day as different elements. How can I do that?

As reference, this is one element, I need something like (2010, 1, 1), hour, minutes, etc don't matter:

tiempo[0]
Out[207]: numpy.datetime64('2010-01-01T12:00:00.000000000')

I tried converting it to timestamp and then to datetime, but I couldn't make it work.

ts = (tiempo - np.datetime64('1970-01-01T00:00:00Z'))// np.timedelta64(1, 's')

Solution

  • you can use pandas to_datetime

    import numpy as np
    import pandas as pd
    
    tiempo = np.datetime64('2010-01-01T12:00:00.000000000')
    date_time = pd.to_datetime(tiempo)
    print(date_time.year, date_time.month, date_time.day)