1

i have the following code where i try and populate an array with dates from 1988-2016

from datetime import datetime, timedelta
t = np.arange(datetime(1988,1,1), datetime(2016,1,1), timedelta(days=365)).astype(datetime)

This gives me the following output:

array([datetime.datetime(1988, 1, 1, 0, 0),
       datetime.datetime(1988, 12, 31, 0, 0),
       datetime.datetime(1989, 12, 31, 0, 0),
                 ....
       datetime.datetime(2015, 12, 25, 0, 0)], dtype=object)

However, for my output i just want to have the year and not the month or day and i dont want that datetime.datetime at the begining. So i am aming for something like this:

array([(1988)
      (1989),
      (1990),
        ...
      (2015)], dtype=object)

How can i achieve this?

Tamarie
  • 125
  • 2
  • 6
  • 18

2 Answers2

1

Use numpy.datetime64.

import numpy as np
t = np.arange('1988','2016',dtype='datetime64[Y]')

The variable will have the representation

array(['1988', '1989', '1990', '1991', '1992', '1993', '1994', '1995',
   '1996', '1997', '1998', '1999', '2000', '2001', '2002', '2003',
   '2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011',
   '2012', '2013', '2014', '2015'], dtype='datetime64[Y]')

You can then change the formatter of datetime

np.set_printoptions(formatter={'datetime': lambda x: '('+str(x)+')'})

The variable will now be formatted as

array([(1988), (1989), (1990), (1991), (1992), (1993), (1994), (1995),
   (1996), (1997), (1998), (1999), (2000), (2001), (2002), (2003),
   (2004), (2005), (2006), (2007), (2008), (2009), (2010), (2011),
   (2012), (2013), (2014), (2015)], dtype='datetime64[Y]')
Eri
  • 48
  • 5
0

This should give you an array of both the years as datetime objects.

year_objects = []
num_years = 20
start_year = 1988
for i in range(num_years):
    x = datetime.datetime(start_year + i, 1, 1)
    year_objects.append(x) 
CobraPi
  • 372
  • 2
  • 9