Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round datetime64 array to nearest second

I have an array of type datetime64[ns]. Each element looks something like '2019-08-30T14:02:03.684000000'. How do I round the values to the nearest second such that I would obtain '2019-08-30T14:02:04' in this example?

I know I can truncate the values by

t = t.astype('datetime64[s]')

but I specifically need to round the values and not truncate them. And the numpy 'round' function doesn't seem to like the datetime64[ns] data type.

like image 263
Hypermale Avatar asked Feb 07 '26 03:02

Hypermale


2 Answers

You can do it by converting np.datetime64 to datetime.datetime.

import numpy as np
from datetime import datetime, timedelta

dt64 = np.datetime64('2019-08-30T14:02:03.684000000')

# np to datetime object
ts = (dt64 - np.datetime64('1970-01-01T00:00:00Z')) / np.timedelta64(1, 's')
dt = datetime.utcfromtimestamp(ts)

# Rounding
if dt.microsecond/1000000 > 0.5:
  date = (dt + timedelta(seconds=1)).replace(microsecond=0)
else:
  date = dt.replace(microsecond=0)

# Datetime to np 
date_rounded = np.datetime64(date).astype('datetime64[s]')

Output:

numpy.datetime64('2019-08-30T14:02:04')

like image 169
Nischal Sanil Avatar answered Feb 08 '26 17:02

Nischal Sanil


You can use round function from the .dt-accessor:

import pandas as pd
t = pd.Series(['2019-08-30T14:02:03.684000000'], dtype='datetime64[ns]')
# 0   2019-08-30 14:02:03.684
# dtype: datetime64[ns]

t.dt.round('s')
# 0   2019-08-30 14:02:04
# dtype: datetime64[ns]
like image 45
qaziqarta Avatar answered Feb 08 '26 15:02

qaziqarta