maynull
maynull

Reputation: 2046

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?

Upvotes: 8

Views: 30774

Answers (1)

cs95
cs95

Reputation: 403128

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) 

Upvotes: 15

Related Questions