如何将Date字符串转换为DateTime对象? [英] How to convert a Date string to a DateTime object?

查看:121
本文介绍了如何将Date字符串转换为DateTime对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下日期:

2005-08-11T16:34:33Z

我需要知道这是日期是在datetime(2009,04,01)之前还是之后,我可以似乎找到一种方法可以将该字符串转换成某种有意义的方式将其与 datetime(2009,04,01)进行比较。

I need to know if this is date is before or after datetime(2009,04,01) and I can't seem to find a method that will convert that string to something that lets me compare it to datetime(2009,04,01) in a meaningful way.

推荐答案

由于字符串是ISO格式,因此可以直接与ISO格式版本的 datetime 你提到:

Since the string is in ISO format, it can be meaningfully compared directly with the ISO format version of the datetime you mention:

>>> s='2005-08-11T16:34:33Z'
>>> t=datetime.datetime(2009,04,01)
>>> t.isoformat()
'2009-04-01T00:00:00'
>>> s < t
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't compare datetime.datetime to str
>>> s < t.isoformat()
True
>>> z='2009-10-01T18:20:12'
>>> z < t.isoformat()
False

如您所见,而您无法比较字符串使用datetime对象,只要字符串是ISO格式,将它们与datetime对象的 .isoformat()进行比较是很好的。这是日期和时间的ISO格式字符串表示形式的美丽:它正确的可比性和正确排序作为字符串,而不一定要求转换为其他类型。

as you see, while you can't compare string with datetime objects, as long as the strings are in ISO format it's fine to compare them with the .isoformat() of the datetime objects. That's the beauty of the ISO format string representation of dates and times: it's correctly comparable and sorts correctly as strings, without necessarily requiring conversion into other types.

如果您希望转换,您当然可以:

If you're keen to convert, of course, you can:

>>> datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%SZ')
datetime.datetime(2005, 8, 11, 16, 34, 33)

这篇关于如何将Date字符串转换为DateTime对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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