简体   繁体   中英

How to convert an array of datetimes to a list of specific date format

my present array is given below:

 print(alldates)

Its output:

array([datetime.date(2019, 1, 25), datetime.date(2019, 1, 26),
       datetime.date(2019, 1, 27), datetime.date(2019, 1, 29),
       datetime.date(2019, 1, 31), datetime.date(2019, 2, 1)], dtype=object)

I want to convert it to something like this:

alldates = ['2019-01-25'.....,'2019-02-01']

Use an .astype(str) :

print(alldates.astype(str))

Which outputs:

['2019-01-25' '2019-01-26' '2019-01-27' '2019-01-29' '2019-01-31'
 '2019-02-01']

you can use str() transfer to string and then append to new array

import datetime

alldates=[datetime.date(2019, 1, 25), datetime.date(2019, 1, 26),datetime.date(2019, 1, 27), datetime.date(2019, 1, 29),datetime.date(2019, 1, 31), datetime.date(2019, 2, 1)]

new_allldates = []
for item in alldates:
    new_allldates.append(str(item))

print(new_allldates)

Result:

['2019-01-25', '2019-01-26', '2019-01-27', '2019-01-29', '2019-01-31', '2019-02-01']

You can achieve the result by using below code,

datelist = [datetime.date(2019, 1, 25), datetime.date(2019, 1, 26),datetime.date(2019, 1, 27), datetime.date(2019, 1, 29),datetime.date(2019, 1, 31), datetime.date(2019, 2, 1)]

resultlist = [i.strftime('%d-%m-%Y') for i in datelist]

print(resultlist)

Result :

['25-01-2019', '26-01-2019', '27-01-2019', '29-01-2019', '31-01-2019', '01-02-2019']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM