ItsBigBrainTime
ItsBigBrainTime

Reputation: 15

How to format dates differently?

I'm working with Python and I have a list of dates in year-month-day format, and I want to convert it to just year-month. So the beginning of my list looks like this: ['2020-02-26', '2020-02-27', '2020-02-28', '2020-02-29', '2020-03-02', '2020-03-03'....

and I want it to become this: ['2020-02', '2020-02', '2020-02', '2020-02', '2020-03', '2020-03'...

I am not sure where to start, and I'm thinking regex might be the solution, but I'm awful with it and I don't understand it.

I have months going all the way up to December, if that changes anything. Thanks for any help!

Upvotes: 0

Views: 53

Answers (4)

Grinnex.
Grinnex.

Reputation: 1049

Since the dates you are using are in a string format, you can always remove the last 3 characters on each date string. Obviously with a for cycle to go through the array. Someting like this:

dates = ['2020-12-31', '2021-01-31'];

for date in range(len(dates)):
    dates[date] = dates[date][:-3]

print(dates)

The previous code will output: ['2020-12', '2021-01']

Upvotes: 0

Kalyan Saha
Kalyan Saha

Reputation: 64

You already know the required date length, so slicing can be used.

dates = ['2020-02-26', '2020-02-27', '2020-02-28', '2020-02-29', '2020-03-02', '2020-03-03']
newdates = [date[0:7] for date in dates]
print(newdates)

Output:

['2020-02', '2020-02', '2020-02', '2020-02', '2020-03', '2020-03']

Upvotes: 0

Sam Gomena
Sam Gomena

Reputation: 1479

If you know your dates will always be formatted as yyyy-mm-dd you could simply map a string split to each item in the list:

year_month_day = ['2020-02-26', '2020-02-27', '2020-02-28', '2020-02-29', '2020-03-02', '2020-03-03']
year_month = list(map(lambda date: "-".join(date.split("-")[:-1]), year_month_day))

This works by removing everything after the last - for each item in the array.

Upvotes: 1

Nick
Nick

Reputation: 147166

If your dates are all in that fixed format, it's probably simplest just to slice off the day part:

dates = ['2020-02-26', '2020-02-27', '2020-02-28', '2020-02-29', '2020-03-02', '2020-03-03']
out = [d[:-3] for d in dates]

Output:

['2020-02', '2020-02', '2020-02', '2020-02', '2020-03', '2020-03']

Upvotes: 5

Related Questions