Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

python - How to convert a Date string to a DateTime object?

I have following date:

2005-08-11T16:34:33Z

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...