How to get rid of extraneous zeroes in dates?

Viewed 69

I have this list of dates that I need to compare to another list that doesn't have extraneous zeroes. I would like to take the extraneous zeroes out of the first list. How can I do this easily? Would it be faster to convert the other list so that it has extraneous zeroes?

2 Answers

Try this to remove all the extraneous leading zeros without using datetime:

for i in range(len(date_lst)):
  date_lst[i] = '/'.join([x.lstrip('0') for x in date_lst[i].split('/')])

For the one-liners:

date_lst = ['/'.join([y.lstrip('0') for y in x.split('/')]) for x in date_lst]

You can convert them into datetime objects. The datetime.strptime() function lets you create one from a string, where you also feed in the format of that date string. For example:

from datetime import datetime

x = datetime.strptime('06/13/2015', '%m/%d/%Y')
y = datetime.strptime('3/1/2015', '%-m/%-d/%Y')

and then you can compare x and y with normal operators like <. You can also convert an entire list of strings like this via list comprehension: converted_dates = [datetime.strptime(d, '%m/%d/%Y') for d in list_of_dates]

edit: you can also convert them back into strings with strftime, for example x.strftime('%-m/%-d/%Y') would give '6/13/2015'

Related