Home > Mobile >  How to change format of a numpy array of date from YYYY-MM-DD to MM - YY
How to change format of a numpy array of date from YYYY-MM-DD to MM - YY

Time:03-15

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' ....

CodePudding user response:

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)
  • Related