8

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 1

15

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) 
Sign up to request clarification or add additional context in comments.

4 Comments

This doesn't yield the possibility of using np.datetime with base units like days, since Pandas is set up to cast to nanosecond resolution. Does there exist a similarly easy way to parse np.datetime objects from string?
The work-around I found is to use the pd.to_datetime function as suggested by @cs95 and then use strftime function to customize the format extracted. For example, dt.strftime('%Y-%m') to keep only Year, Month.
@ifly6 You can always use pd.to_datetime(date).to_numpy().
Doesn't solve the problem. Pandas will throw out of bounds exception when parsing date

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.