20

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.

Bhavesh Odedra
  • 10,990
  • 12
  • 33
  • 58

3 Answers3

36

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)
Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
1

I'd recommend taking a look at: http://dateutil.readthedocs.io/en/stable/parser.html

from dateutil.parser import parse datetime = parse("Sat Oct 11 17:13:46 UTC 2003")

Lukas N.P. Egger
  • 923
  • 2
  • 9
  • 12
0

If you know the string just use the datetime.datetime(year, month, day, hour, minute, second) function. Split your string to get the appropriate variables and put it in to make it a datetime type. Then just compare it against whatever you need.

Or you can use the iso format as people have suggested also.

The Jug
  • 1,105
  • 3
  • 12
  • 26
  • Thank you Jug. That is how I have been doing it but knew there must be something more elegant out there. And, Alex provided it. :) –  Apr 27 '10 at 14:12
  • You're welcome! Alex's is definitely the more elegant solution. I wasn't positive of how the iso format worked off the top of my head and am away from my normal computer to check. – The Jug Apr 27 '10 at 14:22