1

I am trying to have a list of dates printed out across a google spreadsheet, so far I have the following script, which works fine in getting a list of dates, but I need to know how to convert this list of dates into a list of strings..

def daterange(startdate, enddate):
    r = (enddate+datetime.timedelta(days=1)-startdate).days
    return [startdate+datetime.timedelta(days=i) for i in range(r)]


startdate = datetime.date(2018, 11, 19)
enddate = datetime.date(2018,11,25)
datelist = daterange(startdate, enddate)

print ([str(date) for date in datelist])

I would have thought that 'str(date) would have accomplished this but it is still a list of dates..I am not an experienced programmed so please explain simply.

** EDIT

I realized my error.. It was printing a string fine, but as far as I can tell I need the dates to be stored as strings first, and then to update the spreadsheet with a list of strings.. I actually didn't need to use the print function at all (and I haven't with other lists of strings I've worked with on this project)Can anyone show me how to convert and store these dates as strings?

3

2 Answers 2

3

This line is ok:

print ([str(date) for date in datelist])

These are other ways you could print out the datelist:

print ([date.strftime('%Y-%m-%d') for date in datelist])
print ([str(date) for date in datelist])
print (["%s" % date for date in datelist])
print ([date for date in datelist])
print (datelist)

The last two examples results in this output:

[datetime.date(2018, 11, 19), datetime.date(2018, 11, 20), datetime.date(2018, 11, 21), datetime.date(2018, 11, 22), datetime.date(2018, 11, 23), datetime.date(2018, 11, 24), datetime.date(2018, 11, 25)]
Sign up to request clarification or add additional context in comments.

1 Comment

I realised my error.. It was printing a string fine, but as far as I can tell I need the dates to be stored as strings first, and then to update the spreadsheet with a list of strings.. I actually didn't need to use the print function at all (and I haven't with other lists of strings I've worked with on this project)
1

Take a look at https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior

With this you can convert a date to your desired string format. Loop over your list again and turn them all into string variants.

for date in datelist:
    print(data.strftime("%B %d, %Y"))

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.