Home > database >  How to convert the format all the values in a date-time array?
How to convert the format all the values in a date-time array?

Time:01-15

This is my data :

dates = np.arange("2018-01-01", "2021-12-31", dtype="datetime64[D]")

I now want to convert from : "2018-01-01" -> "Jan-01-2018" ["Monthname-day-year"] format

How to i do this ? Is it possible to initialize this in the way we want to convert ? Can i use something like:

for i in dates:
   i =  i.replace(i.month,i.strftime("%b"))

CodePudding user response:

You can try this:

from datetime import datetime

dates = np.arange("2018-01-01", "2021-12-31", dtype="datetime64[D]")
result_dates = []
for date in dates.astype(datetime):
    result_dates.append(date.strftime("%b-%d-%Y"))

But you will need to convert result dates as shown in the code

CodePudding user response:

You can do something like

  for i in range(len(dates)):
    dates[i] = dates[i].strftime("%b-%d-%Y")

This will convert each date in the dates array to a string in the format "Monthname-day-year" (e.g., "Jan-01-2018"). The strftime() method takes a format string as an argument, in this case "%b-%d-%Y", where %b is the abbreviated month name, %d is the day of the month as a zero-padded decimal number, and %Y is the year with century as a decimal number.

It's worth noting that the above code will change the original array to the desired format and if you want to retain the original data then you can create a new array and store the formatted dates in that array.

  • Related