How to create a new numpy timedelta (np.timedelta64) object
There are two basic ways to create a new np.timedelta64 object:
Construct directly:
create_numpy_timedelta.py
import numpy as np
my_timedelta = np.timedelta64(625, 'us')Note that the constructor will only work with ints, i.e. np.timedelta64(625.5, 'us') won’t work. See
Construct as a difference between two np.datetime64 objects:
See How to get current datetime as numpy datetime (np.datetime64) for more details on how to get the current datetime as np.datetime64.
For any two np.datetime64 instances, we can compute the difference using
example.py
from datetime import datetime
import numpy as np
# There will be a minimal time difference between those two
dt1 = np.datetime64(datetime.now())
dt2 = np.datetime64(datetime.now())
my_timedelta = dt2 - dt1
print(my_timedelta) # For me, this prints "16 microseconds"Check out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow