将未知格式的日期字符串转换为datetime [英] Converting date string in unknown format to datetime

查看:80
本文介绍了将未知格式的日期字符串转换为datetime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个通用的自定义 strToDatetime(string)函数.日期字符串可能采用某些不同的格式.两种最流行的替代方法似乎是 datetime.strptime(string,format) dateutil.parser(string).似乎 datetime.strptime()需要一种格式,而 dateutil.parser()不需要,因此可能的解决方案似乎是:

I'm building a generic custom strToDatetime(string) function. The date string may be in some different formats. The 2 most popular alternatives seem datetime.strptime(string, format) and dateutil.parser(string). It seems datetime.strptime() requires a format and dateutil.parser() does not, so the possible solutions seem to be:

  1. 测试日期字符串模式以查找日期字符串格式,并使用 datetime.strptime()
  2. 使用 dateutil.parser()

这是正确的吗?备选方案1(较硬,将来可能需要维护)是否具有诸如性能之类的优势?

Is this correct? Alternative 1 (harder and may require maintenance in the future) has advantages, such as performance?

推荐答案

dateutil的 parse()方法非常灵活,可以解析几乎所有您扔给它的东西.

The parse() method of dateutil is very flexible and will parse almost anything you throw at it.

但是,由于这种灵活性,如果您的输入仅限于一定数量的模式,则检查这些模式的自定义代码随后会使用 datetime.datetime.strptime()轻松击败它.

However, because of that flexibility, if your input is limited to a certain number of patterns, custom code that checks for those patterns then uses datetime.datetime.strptime() could easily beat it.

由于这完全取决于您需要测试的模式数量,因此您唯一可以做的就是 measure ,对于您的特定用例,这种方法会更快. .

Since this depends entirely on the number of patterns you need to test for, the only thing you can do is measure which one will be faster for your specific usecases.

这篇关于将未知格式的日期字符串转换为datetime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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