1

I've been trying to input into a mysql table using python, thing is I'm trying to create a list with all dates from April 2016 to now so I can insert them individually into the sql insert, I searched but I didn't find how can I change value per list result (if it's 1 digit or 2 digits):

dates = ['2016-04-'+str(i+1) for i in range(9,30)] 

I would like i to add a 0 every time i is a single digit (i.e 1,2,3 etc.) and when its double digit for it to stay that way (i.e 10, 11, 12 etc.)

3 Answers 3

1
dates = ['2016-04-'+ '{:02d}'.format(i) for i in range(9,30)]

>>> print dates
['2016-04-09', '2016-04-10', '2016-04-11', '2016-04-12', '2016-04-13', '2016-04-14', '2016-04-15', '2016-04-16', '2016-0
4-17', '2016-04-18', '2016-04-19', '2016-04-20', '2016-04-21', '2016-04-22', '2016-04-23', '2016-04-24', '2016-04-25', '
2016-04-26', '2016-04-27', '2016-04-28', '2016-04-29']
>>>
Sign up to request clarification or add additional context in comments.

Comments

0

Using C style formatting, all the dates in April:

dates = ['2016-04-%02d'%i for i in range(1,31)]

Need range(1,31) since the last value in the range is not used, or use range(30) and add 1 to i.

The same using .format():

dates = ['2016-04-{:02}'.format(i) for i in range(1,31)]

Comments

0

You can use dateutil module

from datetime import datetime
from dateutil.rrule import rrule, DAILY
start_date = datetime(2016,04,01)
w=[each.strftime('%Y-%m-%d') for each in list(rrule(freq=DAILY, dtstart=start_date, until=datetime(2016,05,9)))]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.