0

I am shocked at how long I've been running around down various rabbit holes trying to figure this problem out which (I thought) should be relatively simple.

I have a numpy array of strings saved as variable t with some associated data as raw_data:

t = array(['20141017000000','20141017000001','20141017000002'],dtype='<U14')
raw_data = np.array([1,2,3],dtype='float')

The date format is YYYYmmddHHMMSS

I just want to convert this to a datetime object that is compatible with matplotlib for plotting purposes.

Various answers I've found inevitably lead to errors including:

Option #1

import matplotlib.dates as dates
convertedDate = dates.num2date(t)

Error: can't multiply sequence by non-int of type 'float'

Option #2 (from here)

from datetime import datetime
convertedDate = datetime.strptime(t, '%YY%mm%dd%HH%MM%ss')
Error: strptime() argument 1 must be str, not numpy.ndarray

Option #3 (from here)

import numpy as np
convertedDate = [np.datetime64(x) for x in t]

While this option 3 works, the output doesn't quite make sense to me since it looks identical to the original string for example convertedDate[0] returns numpy.datetime64('20141017000000'). And furthermore when I try to plot it I get this:

import matplotlib.pyplot as plt
plt.plot(convertedDate,raw_data)
OverflowError: int too big to convert

Any help is appreciated.

Darcy
  • 619
  • 2
  • 5
  • 15

2 Answers2

1

You can use pandas:

# pip install pandas
import pandas as pd

dti = pd.to_datetime(t, format='%Y%m%d%H%M%S')

Output:

>>> dti
DatetimeIndex(['2014-10-17 00:00:00', '2014-10-17 00:00:01',
               '2014-10-17 00:00:02'],
              dtype='datetime64[ns]', freq=None)

>>> dti.values
array(['2014-10-17T00:00:00.000000000', '2014-10-17T00:00:01.000000000',
       '2014-10-17T00:00:02.000000000'], dtype='datetime64[ns]')
Corralien
  • 109,409
  • 8
  • 28
  • 52
-1

I guess you can use this method datetime.strptime(date_string, format)

paleonix
  • 2,293
  • 1
  • 13
  • 29
  • 2
    You can improve your answer by providing an example of your solution for others to use. [How do I write a good answer to a question?](https://meta.stackexchange.com/q/7656) – Corralien May 03 '23 at 07:05