Look at datetime.datetime.strptime.
You just need to write a format spec for each format, convert both values to
datetime objects, and compare them. (You could convert one string format to the other and compare the strings, but that's not as good as idea, as I'll explain below.)
>>> import datetime
>>> fmt1 = '%Y-%m-%d %H:%M:%S.%f'
>>> fmt2 = '%H:%M:%S %a %b %d %Y'
>>> s1 = '2012-11-12 15:16:08.648521'
>>> s2 = '14:44:02 Mon Nov 12 2012'
>>> dt1 = datetime.datetime.strptime(s1, fmt1)
>>> dt2 = datetime.datetime.strptime(s2, fmt2)
>>> cmp(dt1, dt2)
datetime.datetime(2012, 11, 12, 15, 16, 8, 648521)
datetime.datetime(2012, 11, 12, 14, 44, 2)
Note that one of your time formats includes microseconds and the other doesn't, which means they will only actually be equal if the first one happens to be exactly at the second mark (ends with
.000000). How to deal with that depends on what you're trying to do.
For example, if you want to round to to the nearest second, you can do something like this:
dt1 = datetime.datetime(dt1.year, dt1.month, dt1.day,
dt1.second + (1 if dt1.microsecond >= 500000 else 0), 0)
Or, if you want to check for equality within a certain delta range:
abs(dt2 - dt1) < datetime.timedelta(0, 1)
One more problem you may run into is timezones. If one of those dates is local, and the other is GMT, you have to convert one or the other after parsing.
Your original question is asking how to convert one format to the other. You could do this, and then compare them as strings, but it's much better to compare them as actual
datetime values. For one thing, if you convert them both to the second format, they don't even compare properly as strings (
14:44:02 Mon Nov 12 2012 is less than
15:44:02 Sun Nov 11 2012 even though it's 23 hours later). It also makes dealing with microseconds, time zones, etc. a lot more complicated. But if you really want to do it,
strftime is the opposite function to
>>> datetime.datetime.strftime(dt2, fmt1)