Home > Back-end >  Getting full seconds and microseconds from Numpy datetime64
Getting full seconds and microseconds from Numpy datetime64

Time:05-04

I need to get a timedelta as a full float of seconds and microseconds, for instance 2.786 seconds. Doing this with datetime64's specifying 'ms' as milliseconds

elapsed_time = np.datetime64(dial_1, 'ms') - np.datetime64(dial_2, 'ms')

Gives me numpy.timedelta64(-2786,'ms') Great, but I need that in seconds. Doing that now by specifying seconds

elapsed_time = np.datetime64(dial_1, 's') - np.datetime64(dial_2, 's')

Now gives numpy.timedelta64(-3,'s') and has rounded it upto a whole 3 seconds. I just want to know how to get the decimal 2.786 seconds

Any help much appreciated

CodePudding user response:

IIUC divide difference by 1 second:

dial_1 = 0
dial_2 = 2786
elapsed_time = (np.datetime64(dial_1, 'ms') - np.datetime64(dial_2, 'ms')) / np.timedelta64(1, 's')
print (elapsed_time)
-2.786

CodePudding user response:

Relation in second & milisecond

  1. 1 second = 1000 milisecond and 1 milisecond = 1/1000 second
  2. 2.786 second = 2786 milisecond

If we take 2 dials i.e dial_1=0 milisecond and dial_2=2786 milisecond, then

output in milisecond-->

import numpy as np

dial_1 = 0
dial_2 = 2786
elapsed_time = np.datetime64(dial_1, 'ms') - np.datetime64(dial_2, 'ms')
print(elapsed_time)

OUTPUT:
    -2786 milliseconds

if we need output in float then we can't assign float value i.e dial_2=2.786 because np.datetime64(2.786, 's') give error i.e ValueError: Could not convert object to NumPy datetime

if we need output in float then use timedelta64

timedelta64 are a number, to represent the number of units, and a date/time unit, such as (D)ay, (M)onth, (Y)ear, (h)ours, (m)inutes, or (s)econd

dial = 1000 milisecond = dial = 1 second

output in second-->

import numpy as np

dial_1 = 0
dial_2 = 2786
dial = 1000
elapsed_time = (np.datetime64(dial_1, 's') - np.datetime64(dial_2, 's'))/(np.timedelta64(dial, 's'))
print(elapsed_time)

OUTPUT:
    -2.786
  • Related