Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to NumPy datetime64 dtype

I program gets a string of current time every minute as date = '201711081750'

I want to store these strings as np.datetime64 into an array.

I think I could convert this kind of strings as

>>> date = '201711081750'

>>> np.datetime64( date[:4] +'-'+date[4:6]+'-'+date[6:8]+' ' +date[8:10]+':'+date[10:]  , 'm' )
numpy.datetime64('2017-11-08T17:50')

But it looks complicated and I think it might engender errors later.

Are there simpler ways to do this?

like image 511
maynull Avatar asked Jan 04 '23 05:01

maynull


1 Answers

pd.to_datetime

import pandas as pd

pd.to_datetime(date, format='%Y%m%d%H%M')
Timestamp('2017-11-08 17:50:00')

The important bit here is the format string '%Y%m%d%H%M'.


datetime.datetime equivalent in python.

from datetime import datetime as dt

dt.strptime(date, '%Y%m%d%H%M')
datetime.datetime(2017, 11, 8, 17, 50) 
like image 141
cs95 Avatar answered Jan 21 '23 03:01

cs95