Problem with datetime module - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Problem with datetime module (/thread-11744.html) |
Problem with datetime module - PierreSoulier - Jul-24-2018 Hello, i have a csv file. It represents events that happen in France. One column contains date written like so 'YYYY-MM-DD'. I want to delete every row that has a date difference of at least 60 days from today. I have created this program that from the string 'YYYY-MM-DD' return the difference in days from today. date ='2018-08-26' liste = date.split('-') print(liste) liste2 = [] liste2.append(int(liste[0])) liste2.append(int(liste[1].replace('0',''))) liste2.append(int(liste[2].replace('0',''))) print(liste2) test = datetime.now() - datetime(liste2[0], liste2[1], liste2[2]) print(test) if test[0] > 60 : print("delete")And I get this error: ['2018', '08', '26'] [2018, 8, 26] -33 days, 9:52:04.046700 Traceback (most recent call last): File "untitled2.py", line 20, in <module> if test[0] > 60 : TypeError: 'datetime.timedelta' object is not subscriptableI don't know how to "extract" the number of days, do you have any idea? Thank you RE: Problem with datetime module - buran - Jul-24-2018 import datetime def is_more_60days(my_date): test_date = datetime.datetime.strptime(my_date, '%Y-%m-%d') date_diff = datetime.datetime.now() - test_date if date_diff > datetime.timedelta(days=60): print("delete {}".format(my_date)) return date_diff.days > 60 test_date ='2017-08-26' test_date2 = '2018-05-30' print('{} is more than 60 days away: {}'.format(test_date, is_more_60days(test_date))) print('{} is more than 60 days away: {}'.format(test_date2, is_more_60days(test_date2)))compare timedelta.days with 60 or compare two timedeltas (I use both ways in the example above) RE: Problem with datetime module - PierreSoulier - Jul-24-2018 Oh ok I see :) Thank you ! RE: Problem with datetime module - perfringo - Jul-24-2018 import datetime ... date_diff = datetime.datetime.now() - test_date ...I was writing similar answer but was ninjad by buran :-). Very good answer and I like it. Observation / nitpicking: it is matter of preference but one option is to use datetime.datetime.today() which is for me personally more in line with 'explicit is better than implicit'. I am not speaking english natively so for me 'today' is associated with date and 'now' with time. However, it is a matter of expected behaviour of code rather than personal biases.
|