-1

I am trying to parse this "For The Year Ending December 31, 2015" and convert it to 2015-12-31 using the datetime lib. How would I go about partitioning and then converting the date? My program is looking through an excel file with multiple sheets and combining them into one; however, there is need now to add a date column, but I can only get it write the full value to the cell. So my data column currently has "For The Year Ending December 31, 2015" in all the rows.

Thanks in advance!

Here is the code block that is working now. Thanks all! edited to account for text that could vary.

   if rx > (options.startrow-1):
            ws.write(rowcount, 0, sheet.name)
            date_value = sheet.cell_value(4,0)
            s = date_value.split(" ")
            del s[-1]
            del s[-1]
            del s[-1]
            string = ' '.join(s)

            d = datetime.strptime(date_value, string + " %B %d, %Y")
            result = datetime.strftime(d, '%Y-%m-%d')
            ws.write(rowcount, 9, result)
            for cx in range(sheet.ncols):
antone king
  • 83
  • 11
  • Please share what you have attempted so far with you complete code included. – Vaibhav Bajaj Aug 16 '16 at 21:48
  • Please have a look at this. I hope this helps. http://stackoverflow.com/questions/2265357/parse-date-string-and-change-format?noredirect=1&lq=1 – Ehsan Aug 16 '16 at 21:53

2 Answers2

4

Simply include the hard-coded portion and then use the proper identifiers:

>>> import datetime
>>> s = "For The Year Ending December 31, 2015"
>>> d = datetime.datetime.strptime(s, 'For The Year Ending %B %d, %Y')
>>> result = datetime.datetime.strftime(d, '%Y-%m-%d')
>>> print(result)
2015-12-31
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
2
from datetime import datetime

date_string = 'For The Year Ending December 31, 2015'
date_string_format = 'For The Year Ending %B %d, %Y'
date_print_class = datetime.strptime(date_string, date_string_format)
wanted_date = datetime.strftime(date_print_class, '%Y-%m-%d')

print(wanted_date)
double_j
  • 1,636
  • 1
  • 18
  • 27