1

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?

1 Answer 1

1

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]')
Sign up to request clarification or add additional context in comments.

2 Comments

thank you that works! One technical question: why would Option1 not work if day0 is '1970-01-01T00:00:00'?
@Swawa the date string has to be changed in both day0 declaration and in the verification part.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.