简体   繁体   中英

how to get string value from a list in python

result = [{'start_date': datetime.date(2019, 1, 20)}, {'start_date': datetime.date(2019, 1, 21)}]

我想以列表格式获得输出:

result = ['2019-1-20', '2019-1-21']

Cast type to str :

result = str(result[0]['start_date'])

or

result = str(result[0].get('start_date']))

Use Below code:

[print("Result :",Dict["start_date"]) for Dict in result]

Output:

Result : 2019-01-20
Result : 2019-01-21

I would use strftime to format your dates to what your desired form:

import datetime

result = [{'start_date': datetime.date(2019, 1, 20)}, {'start_date': datetime.date(2019, 1, 21)}]

for date_val in result:
    print date_val['start_date'].strftime('%Y-%m-%d')

# Results
2019-01-20
2019-01-21

If you want just the first element:

print result[0]['start_date'].strftime('%Y-%m-%d')

See: strftime documentation

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