Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 962
Merlin Avatar asked Aug 25 '26 01:08

Merlin


2 Answers

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]))
like image 174
Judge Maygarden Avatar answered Aug 27 '26 16:08

Judge Maygarden


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'])
like image 34
unutbu Avatar answered Aug 27 '26 16:08

unutbu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!