如何处理python系列中的多个日期字符串格式 [英] How to deal with multiple date string formats in a python series
问题描述
此start_date系列中的条目的两个示例: p>
9/11/15
9/11/15 0:00
如何识别这些格式并相应对待?
不幸的是,您只需要尝试每种格式即可。如果您提供示例格式, strptime 将尝试解析为您讨论这里。
代码最终将如下所示:
import datetime
POSSIBLE_FORMATS = ['%m /%d /%Y','%Y /%m /%d'等...]日期可能在$ b的所有格式
$ b在POSSIBLE_FORMATS中的格式:
try:
parsed_date = datetime.strptime(raw_string_date,format)#尝试获取日期
break#如果格式正确,不要测试任何其他格式
除了ValueError:
传递#如果格式不正确,继续尝试其他格式
I have a csv file which I am trying to complete operations on. I have created a dataframe with one column titled "start_date" which has the date of warranty start. The problem I have encountered is that the format of the date is not consistent. I would like to know the number of days passed from today's calendar date and the date warranty started for this product.
Two examples of the entries in this start_date series:
9/11/15
9/11/15 0:00
How can I identify each of these formats and treat them accordingly?
Unfortunately you just have to try each format it might be. If you give an example format, strptime will attempt to parse it for you as discussed here.
The code will end up looking like:
import datetime
POSSIBLE_FORMATS = ['%m/%d/%Y', '%Y/%m/%d', etc...] # all the formats the date might be in
for format in POSSIBLE_FORMATS :
try:
parsed_date = datetime.strptime(raw_string_date, format) # try to get the date
break # if correct format, don't test any other formats
except ValueError:
pass # if incorrect format, keep trying other formats
这篇关于如何处理python系列中的多个日期字符串格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!