python-3.xnumpy-ndarraypython-datetime

numpy.ndarray of seconds of a day to datetime format


I have a Python numpy.ndarray of seconds of the day with a bunch of decimal seconds:

import numpy as np

sec = [40389.66574375, 40390.12063928, 40391.32714992, 40392.64457077, 40393.48519607, 40394.20021267]
UTCs = np.array([sec])

which gives the array when printed

print(UTCs)
[[40389.66574375 40390.12063928 40391.32714992 40392.64457077
  40393.48519607 40394.20021267]]

This array I would like to change into a datetime format. But something like

mytime = np.datetime64('1970-01-01T00:00:00') + UTCs

will not work as UTCs is not an integer number. The seconds could be reduced down to three decimals but not less. Any hint for me how I would gain a datetime format out of that?


Solution

  • Option 1

    Create an array of datetime objects with microseconds resolution and then create the numpy array

    from datetime import datetime
    import numpy as np
    
    sec = [40389.66574375, 40390.12063928, 40391.32714992, 40392.64457077, 40393.48519607, 40394.20021267]
    
    dsec = [datetime.fromtimestamp(x) for x in sec]
    
    utcs = np.array(dsec, dtype='<M8[us]')
    
    print(utcs)
    
    # start at predefined date
    day0 = datetime.fromisoformat('1982-05-15T00:00:00.000000')
    dsec = [datetime.fromtimestamp(day0.timestamp() + x) for x in sec]
    
    utcs = np.array(dsec, dtype='<M8[us]')
    print(utcs)
    
    
    # verify a value
    print((utcs[0] - np.datetime64('1982-05-15T00:00:00')) / np.timedelta64(1, 's'))
    
    print(sec[0])
    
    
    
    ['1970-01-01T08:13:09.665744' '1970-01-01T08:13:10.120639'
     '1970-01-01T08:13:11.327150' '1970-01-01T08:13:12.644571'
     '1970-01-01T08:13:13.485196' '1970-01-01T08:13:14.200213']
    
    ['1982-05-15T11:13:09.665744' '1982-05-15T11:13:10.120639'
     '1982-05-15T11:13:11.327150' '1982-05-15T11:13:12.644571'
     '1982-05-15T11:13:13.485196' '1982-05-15T11:13:14.200213']
    
    40389.665744
    40389.66574375
    

    Option 2

    numpy and modf

    from math import modf
    np.array([np.datetime64(int(t), 's') + np.timedelta64(int(u * 10**6), 'us') for u,t in  [modf(x) for x in sec]])
    
    array(['1970-01-01T11:13:09.665743', '1970-01-01T11:13:10.120639',
           '1970-01-01T11:13:11.327149', '1970-01-01T11:13:12.644570',
           '1970-01-01T11:13:13.485196', '1970-01-01T11:13:14.200212'],
          dtype='datetime64[us]')