在Python中将时间对象与文字字符串进行比较

时间:2014-04-25 02:14:37

标签: python

我试图将当前时间与作为文本字符串给出的值进行比较。我不知道如何把东西带到一个共同点,因为我觉得所获得的时间与简单的文本字符串并不完全相同,即使它在打印时看起来也是如此。

测试代码:

import time
import datetime

def GetTimeAndWeekday(data):
  datetime_now = datetime.datetime.now()
  if data == "hms":
    time_now = datetime.time(datetime_now.hour, datetime_now.minute, datetime_now.second)
    return time_now
  elif data == "hm":
    time_now = datetime.time(datetime_now.hour, datetime_now.minute)
    return time_now
  return datetime_now

data = "hm"
found = GetTimeAndWeekday(data)
print found  # for "hm" this gives current time in HH:MM:00 format, say 05:29:00

# I want to do something like this logic:
if found == "05:29:00":
  print "the same"
else:
  print "not the same"

我该怎么做那个逻辑?

1 个答案:

答案 0 :(得分:1)

使用strftime()

if found.strftime('%I:%M:%S') == "05:29:00":
    print 'the same'
else:
    print 'not the same'