简体   繁体   中英

Converting a list of dates in string to Month, Day, Year in Python

I have a list of dates in a string that looks like this:

Date_List
Out[83]: 
['2015-08-24 00:00:00',
 '2015-08-30 00:00:00',
 '2015-08-22 00:00:00',
 '2015-08-21 00:00:00',
 '2015-08-25 00:00:00',
 '2015-08-29 00:00:00']

I want it to be formatted like this:

Date_List
Out[83]: 
['08-24-2015',
 '08-30-2015',
 '08-22-2015',
 '08-21-2015',
 '08-25-2015',
 '08-29-2015']

I tried Date_List = ['{}-{}-{}'.format(m,d,y) for y, m, d in map(lambda x: str(x).split('-'), Date_List)]

This returns

Date_List
Out[85]: 
['08-24 00:00:00-2015',
 '08-30 00:00:00-2015',
 '08-22 00:00:00-2015',
 '08-21 00:00:00-2015',
 '08-25 00:00:00-2015',
 '08-29 00:00:00-2015']

Anybody know how to convert and ignore the 00:00:00

I also tried

Date_List = (datetime.datetime.strptime(i, "%Y-%m-%d %H:%M:%S") for i in Date_List)
Date_List = (datetime.datetime.strftime(i, "%m-%d-%Y") for i in Date_List)

but this outputs a generator object?

Date_List
Out[91]: <generator object <genexpr> at 0x2047A5A8>

Which means if I run the code I get this error: TypeError: <generator object <genexpr> at 0x1FBCFC38> is not JSON serializable

You're very close; you just need to use a list comprehension on the last line instead of a generator expression.

Date_List = (datetime.datetime.strptime(i, "%Y-%m-%d %H:%M:%S") for i in Date_List)
Date_List = [datetime.datetime.strftime(i, "%m-%d-%Y") for i in Date_List]

I would clean it up like so:

from datetime import datetime
from pprint import pprint

timestamps = [
    '2015-08-24 00:00:00',
    '2015-08-30 00:00:00',
    '2015-08-22 00:00:00',
    '2015-08-21 00:00:00',
    '2015-08-25 00:00:00',
    '2015-08-29 00:00:00',
    ]

dates = (datetime.strptime(ts, '%Y-%m-%d %H:%M:%S') for ts in timestamps)
date_strings = [datetime.strftime(d, '%m-%d-%Y') for d in dates]

pprint(date_strings)

Output:

['08-24-2015',
 '08-30-2015',
 '08-22-2015',
 '08-21-2015',
 '08-25-2015',
 '08-29-2015']

Here's a slightly more generalized way to do it:

from datetime import datetime
from pprint import pprint


def convert_timestamp(ts, from_pattern, to_pattern):
    dt = datetime.strptime(ts, from_pattern)
    return datetime.strftime(dt, to_pattern)


timestamps = [
    '2015-08-24 00:00:00',
    '2015-08-30 00:00:00',
    '2015-08-22 00:00:00',
    '2015-08-21 00:00:00',
    '2015-08-25 00:00:00',
    '2015-08-29 00:00:00',
    ]

date_strings = [convert_timestamp(ts, '%Y-%m-%d %H:%M:%S', '%m-%d-%Y')
                for ts in timestamps]

pprint(date_strings)

Output:

['08-24-2015',
 '08-30-2015',
 '08-22-2015',
 '08-21-2015',
 '08-25-2015',
 '08-29-2015']

EDIT: Order fixed.

EDIT2: Zero padding fixed after Paulo's suggestion

Try:

from dateutil import parser
map(
    lambda d: "{0:02}-{1:02}-{2}".format(d.month, d.day, d.year),
    map(
        lambda d: parser.parse(d),
        dates
    )
)

or

["{0:02}-{1:02}-{2}".format(d.month, d.day, d.year) for d in map(lambda d: parser.parse(d), dates)]

This should do the trick:

['{}-{}-{}'.format(m,d,y) for y, m, d in map(lambda x: x.split()[0].split('-'), Date_List)]

You don't need str(x) because it's already a string. You then split() the string, which by default splits on whitespace, and take the first part ( [0] ). You then split('-') on the hyphens.

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