0

I have the following date list:

[datetime.date(2021, 9, 30), datetime.date(2021, 10, 31),
 datetime.date(2021, 11, 30), datetime.date(2021, 12, 31),
 datetime.date(2022, 1, 31), datetime.date(2022, 2, 28)]

Which I store in an array:

NDateArray = np.array(DateList,dtype=np.datetime64)

['2021-09-30' '2021-10-31' '2021-11-30' '2021-12-31' '2022-01-31'
 '2022-02-28']

Ho do I convert these to

'Sept 21' 'Oct 21' 'Nov 2021' ....
TourEiffel
  • 4,034
  • 2
  • 16
  • 45
  • And you don't just want to format the original list of `datetime.date` instances as strings? – mkrieger1 Mar 15 '22 at 09:21
  • Does this answer your question? [Can't call strftime on numpy.datetime64, no definition](https://stackoverflow.com/questions/28327101/cant-call-strftime-on-numpy-datetime64-no-definition) – mkrieger1 Mar 15 '22 at 09:47

1 Answers1

0

You can do like this :

import pandas as pd
import numpy as np
import datetime

DateList = [datetime.date(2021, 9, 30), datetime.date(2021, 10, 31),
 datetime.date(2021, 11, 30), datetime.date(2021, 12, 31),
 datetime.date(2022, 1, 31), datetime.date(2022, 2, 28)]

NDateList = [np.datetime64(x) for x in DateList]

for i in range(0,len(NDateList)):
    mydate = datetime.datetime.strptime(str(NDateList[i]), '%Y-%m-%d')
    print(mydate.strftime('%b, %y'))

Output :

Sep, 21
Oct, 21
Nov, 21
Dec, 21
Jan, 22
Feb, 22

If you want fullname for month and a year as YYYY, you can do print(mydate.strftime('%B, %Y'))

Output :

September, 2021
October, 2021
November, 2021
December, 2021
January, 2022
February, 2022

Or

if i want to keep what you did in your code you can continue like this :

import pandas as pd
import numpy as np
import datetime

DateList = [datetime.date(2021, 9, 30), datetime.date(2021, 10, 31),
 datetime.date(2021, 11, 30), datetime.date(2021, 12, 31),
 datetime.date(2022, 1, 31), datetime.date(2022, 2, 28)]

NDateArray = np.array(DateList,dtype=np.datetime64)

NDateList =  [str(x.astype('datetime64[D]')) for x in NDateArray]

NewArrayDate = []
for i in range(0,len(NDateList)):
    mydate = datetime.datetime.strptime(str(NDateList[i]), '%Y-%m-%d')

    # append result to new array
    NewArrayDate.append(mydate.strftime('%b, %y'))


print(NewArrayDate)
  • They already have `np.datetime64` instances, not strings, as input, so they don't need to (and can't) use `strptime`. – mkrieger1 Mar 15 '22 at 09:17
  • I edit my answer. it will be correct now –  Mar 15 '22 at 09:45
  • @AchrafBenSalah If you replace the print by `NDateList[i]= mydate.strftime('%b-%y')` it throw the following error : `ValueError: Error parsing datetime string "Sep-21" at position 0` How do you store it in this array ? – TourEiffel Mar 15 '22 at 09:50
  • check the last code. –  Mar 15 '22 at 09:51