转换“未知格式”日期时间对象的字符串? [英] Convert "unknown format" strings to datetime objects?

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

问题描述

这可能是一个非常基本的问题,但是在阅读了文档之后,我仍然不知道该怎么做...

This is probably a very basic question but after reading documentation I still can't figure out how to do it...

我在Python中有两个字符串包含未知格式的日期。我不知道它们的格式,除了我都知道它们都是有效的日期时间表达式。例如,其中一个可能是ISO格式,另一个可能是其他格式。

I have two strings in Python that contain dates of unknown format. I don't know what formats they are in, except I know that both are valid date-time expressions. For example, one of them might be in the ISO format and the other in some other format.

我需要做的就是能够比较日期。将字符串转换为适当的日期时间对象以便可以进行比较的正确方法是什么?

All I need is to be able to compare the dates. What's the correct way to turn strings into appropriate date-time objects so that they can be compared?

谢谢!

推荐答案

dateutil模块具有日期解析器可以解析多种格式的日期字符串。

The dateutil module has a date parser which can parse date strings in many formats.

例如,

In [13]: import dateutil.parser as parser

In [14]: parser.parse("19970902T090000")
Out[14]: datetime.datetime(1997, 9, 2, 9, 0)

In [15]: import datetime as dt

In [16]: now = dt.datetime.now()

In [17]: now.isoformat()
Out[18]: '2012-11-06T15:08:51.393631'

In [19]: parser.parse('2012-11-06T15:08:51.393631')
Out[19]: datetime.datetime(2012, 11, 6, 15, 8, 51, 393631)

In [20]: parser.parse('November 6, 2012')
Out[20]: datetime.datetime(2012, 11, 6, 0, 0)

请注意,某些日期时间字符串可能不明确:例如, 10-09-2003 可能表示10月9日或9月10日。 dateutil 具有像 dayfirst yearfirst 这样的参数来处理:

Note that some datetime strings can be ambiguous: 10-09-2003 could mean October 9 or September 10, for example. dateutil has parameters like dayfirst and yearfirst to handle this:

In [21]: parser.parse("10-09-2003")
Out[21]: datetime.datetime(2003, 10, 9, 0, 0)

In [22]: parser.parse("10-09-2003", dayfirst = True)
Out[22]: datetime.datetime(2003, 9, 10, 0, 0)

In [23]: parser.parse("10-09-03", yearfirst = True)
Out[23]: datetime.datetime(2010, 9, 3, 0, 0)

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

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