简体   繁体   English

使用Python解析字符串并转换日期

[英]Parsing a string and converting a date using Python

I am trying to parse this "For The Year Ending December 31, 2015" and convert it to 2015-12-31 using the datetime lib. 我正在尝试解析“截至2015年12月31日的年度”,并使用datetime lib将其转换为2015-12-31。 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; 我的程序正在浏览具有多个工作表的excel文件,并将它们合并为一个文件。 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. 因此,我的数据列当前在所有行中都有“截至2015年12月31日的年度”。

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):

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
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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM