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?

0

1 Answer

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) 
4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sophia Al-Mansoor

Sophia Al-Mansoor

Global Business & E-Commerce Reporter

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.

Share this article
Twitter Facebook Pinterest