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.
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')
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With