Python: converting nanoseconds to DateTime64 format

I have a column timestampsin seconds (from midnight) with nanosecond corrections such as 34200.934549345, 34205.735545344etc. in a DataFrame df.

These timestampsstart on the same day 2011-01-10.

How can I convert these seconds to the nearest nanosecond in a format DateTime64 numpy?

I would like to have these entries in my df

2011-01-10 9:30:00.934549345
2011-01-10 9:30:05.735545344

I need to perform the exact operation, as in this one, in the SOLUTION section of the asked question.

Is it possible?

+4
source share
3 answers
> df = pd.DataFrame({'seconds_since_midnight': [34200.934549345, 34205.735545344]})
> df['actual_date'] = (df.seconds_since_midnight * 1e9).astype('timedelta64[ns]') + pd.to_datetime('2011-01-10')
> df
   seconds_since_midnight                   actual_date
0            34200.934549 2011-01-10 09:30:00.934549345
1            34205.735545 2011-01-10 09:30:05.735545344

[2 rows x 2 columns]
+5
source

strptime(), , . , . Python 2.6.7, , strptime . 2.7.6, % f . , , 6 .

import datetime DT
def mystrptime(self, val)
  vals = val.split('.')
  if len(vals) == 1:
    dt = DT.datetime.strptime(val, '%Y-%m-%d %H%M%S')
  else:
    nofrag, frag = vals
    length = len(frag)
    if length > 6:
      frag = frag[:5]
      length = len(frag) # This resets length to 6, but is not really needed
    while length < 6:
      frag = frag + '0'
      length += 1
    nofrag_dt = DT.datetime.strptime(nofrag, '%Y-%m-%d %H%M%S')
    dt = nofrag_dt.replace(microsecond=int(frag))
  return dt

Python 2.7.6 % f :

import datetime DT
def mystrptime(self, val)
  vals = val.split('.')
  if len(vals) > 1:
    nofrag, frag = vals
    frag = frag[:5] # This works even if frag is < 6 characters
    val = '.'.join(nofrag, frag)
  dt = DT.datetime.strptime(val, '%Y-%m-%d %H%M%S.%f')
  return dt
+1

datetime.strptime, 3 :

>>> ds
'2011-01-10 9:30:00.934549345'
>>> datetime.datetime.strptime(ds[:-3], '%Y-%m-%d %H:%M:%S.%f')
datetime.datetime(2011, 1, 10, 9, 30, 0, 934549)

, - , , :

>>> datetime.datetime(2011, 1, 10, 9, 30, 0, 934549345)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: microsecond must be in 0..999999

Since you have time in nanoseconds, if you want to convert to Python Datetime objects, you will have to lose this level of accuracy or be forced to create your own workaround.

0
source

Source: https://habr.com/ru/post/1530343/


All Articles