datetime - Sort dates file python -
i have file contains dates , tasks in form
(datetime.datetime(2014, 5, 20, 0, 0), 'laundry') (datetime.datetime(2014, 6, 1, 0, 0), 'exam ')
how can display tasks due within date ( ex. due within week ) in format ?
20/05/2014: laundry
thanks
assuming data list of tuples this:
date_list = [(datetime.datetime(2014, 5, 20, 0, 0), 'laundry'), (datetime.datetime(2014, 6, 1, 0, 0), 'exam '), (datetime.datetime(2014, 4, 20, 0, 0), 'grocery'), (datetime.datetime(2013, 5, 20, 0, 0), 'tv')]
you can sorted list based on dates doing:
sorted_dates = sorted(date_list, key=lambda x: str(x[1]), reverse=true)
here, passing string representation of dates key
sorted
function translates sorting dates sorting of strings. gives you:[(datetime.datetime(2013, 5, 20, 0, 0), 'tv'), (datetime.datetime(2014, 5, 20, 0, 0), 'laundry'), (datetime.datetime(2014, 4, 20, 0, 0), 'grocery'), (datetime.datetime(2014, 6, 1, 0, 0), 'exam ')]
you can format date in format want, using
strftime
method:formatted_dates = [(item[0].strftime("%d/%m/%y"), item[1]) item in sorted_dates]
which gives you:
[('20/05/13', 'tv'), ('20/05/14', 'laundry'), ('20/04/14', 'grocery'), ('01/06/14', 'exam ')]
your final output can obtained looping
formatted_dates
as:for date, task in formatted_dates: print '{}: {}'.format(date, task)
which prints
20/05/13: tv 20/05/14: laundry 20/04/14: grocery 01/06/14: exam
if data sorted, can skip step 2.
to tasks due in week, make use of combination of timedelta objects , filter
function
tasks_in_a_week = filter(lambda x: x[0] > datetime.datetime.now() , x[0] < datetime.datetime.now() + datetime.timedelta(days=7), sorted_dates)
explanation: datetime.datetime.now()
gives todays date. datetime.datetime.now() + datetime.timedelta(days=7)
gives date 7 days today. so, above filter function looks date in sorted_dates
list falls after today , before 7 days today i.e., in week.
Comments
Post a Comment