0

here is my code:

a=np.arange('2017-01-01', '2017-01-09', dtype='datetime64[D]')

I got the following output:

array(['2017-01-01', '2017-01-02', '2017-01-03', '2017-01-04',
       '2017-01-05', '2017-01-06', '2017-01-07', '2017-01-08'], dtype='datetime64[D]')

I want to strip out the years from each element. How can I do that?

AjitKrish
  • 13
  • 4
  • 1
    What does this mean? The datetimes are essentially epoch timestamps it doesn't make any sense to strip out the year. Why would you want to do that? – Andy Hayden Nov 08 '17 at 05:31
  • How is this a duplicate? The link asks about using dates in `linspace`. No mention of that function here. The link is about a range of dates, but that's all. https://stackoverflow.com/q/37964100 – hpaulj Nov 08 '17 at 11:43

1 Answers1

1

The dates in Y units is:

In [870]: a.astype('datetime64[Y]')
Out[870]: array(['2017', '2017', '2017', '2017', '2017', '2017', '2017', '2017'], dtype='datetime64[Y]')

Or subtracting the first date from the rest, gives a timedelta64

In [875]: a-a[0]
Out[875]: array([0, 1, 2, 3, 4, 5, 6, 7], dtype='timedelta64[D]')

tolist converts the array of dates to a list of datetime objects

In [888]: a.tolist()
Out[888]: 
[datetime.date(2017, 1, 1),
 datetime.date(2017, 1, 2),
 datetime.date(2017, 1, 3),
 datetime.date(2017, 1, 4),
 datetime.date(2017, 1, 5),
 datetime.date(2017, 1, 6),
 datetime.date(2017, 1, 7),
 datetime.date(2017, 1, 8)]

Which can be formated as strings

In [889]: [x.strftime('%m-%d') for x in a.tolist()]
Out[889]: ['01-01', '01-02', '01-03', '01-04', '01-05', '01-06', '01-07', '01-08']

There's no datetime64 format that consists of just month and date.

tolist or item on a timedelta64[...]' produces adatetime.timedelta` object.

hpaulj
  • 221,503
  • 14
  • 230
  • 353