Merlin
Merlin

Reputation: 25629

How to change time formats in python?

How do i get the following list

 [datetime.date(2011, 4, 1), datetime.date(2011, 4, 8), datetime.date(2011, 4, 16), datetime.date(2011, 5, 21)]

as

['2011-04','2011-05']

It not only convert to string but remove dups

Upvotes: 3

Views: 3279

Answers (3)

Judge Maygarden
Judge Maygarden

Reputation: 27573

Convert the dates to strings using datetime.date.strftime.

dates = [date.strftime('%Y-%m') for date in dates]

You can remove duplicates by converting the list to a set and then back to a list.

dates = list(set(dates))

Then combine both methods to do it all in one step.

dates = list(set([date.strftime('%Y-%m') for date in dates]))

Upvotes: 6

Håvard
Håvard

Reputation: 10080

>>> dates = [datetime.date(2011, 4, 1), datetime.date(2011, 4, 8), datetime.date(2011, 4, 16), datetime.date(2011, 5, 21)]
>>> set([date.strftime('%Y-%m') for date in dates])
set(['2011-05', '2011-04'])

set turns a list into a set object, removing duplicates. The [date.strftime('%Y-%m') for date in dates] is a list comprehension that turns each date into a string using the strftime function with a year-month pattern.

Upvotes: 1

unutbu
unutbu

Reputation: 879093

In [43]: import datetime

In [44]: dates=[datetime.date(2011, 4, 1), datetime.date(2011, 4, 8), datetime.date(2011, 4, 16), datetime.date(2011, 5, 21)]

In [45]: set([date.strftime('%Y-%m') for date in dates])
Out[45]: set(['2011-04', '2011-05'])

Upvotes: 1

Related Questions