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?

Spencer Wieczorek
  • 21,229
  • 7
  • 44
  • 54
will27272
  • 31
  • 6

2 Answers2

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)]
Red Cricket
  • 9,762
  • 21
  • 81
  • 166
  • 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) – will27272 Nov 22 '18 at 03:01
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"))
Dennis19901
  • 615
  • 6
  • 9