如何处理python系列中的多个日期字符串格式 [英] How to deal with multiple date string formats in a python series

查看:312
本文介绍了如何处理python系列中的多个日期字符串格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个csv文件,我正在尝试完成操作。我创建了一个名为start_date的数据框,其中包含保修开始日期。我遇到的问题是日期格式不一致。我想知道从今天的日历日期开始的天数以及该产品的保修期限。



此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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆