比较Python中的两种时间类型

时间:2018-08-14 20:35:33

标签: python-3.x datetime

我正在尝试创建一个检查当前时间的功能,并告诉我它是在日出,日落,黄昏,黎明和中午之前还是之后。

但是我有点比较如何比较我得到的时间类型:(

有人可以帮我吗?

这是我的代码:

now = datetime.now()
now_time = now.time()

print ('\nTime now is %s \n' % now_time)

city_name = 'Stockholm'

a = Astral()

a.solar_depression = 'civil'

city = a[city_name]

print('Information for %s/%s\n' % (city_name, city.region))

timezone = city.timezone

print('Timezone: %s' % timezone)

print('Latitude: %.02f; Longitude: %.02f\n' % \
(city.latitude, city.longitude))

today = datetime.strptime(time.strftime("%Y-%m-%d"), '%Y-%m-%d')

sun = city.sun(date=datetime.date(today), local=True)

dawn = str(sun['dawn'])[11:-6]
sunrise = str(sun['sunrise'])[11:-6]
noon = str(sun['noon'])[11:-6]
sunset = str(sun['sunset'])[11:-6]
dusk = str(sun['dusk'])[11:-6]

print('Dawn:    %s' % dawn)
print('Sunrise: %s' % sunrise)
print('Noon:    %s' % noon)
print('Sunset:  %s' % sunset)
print('Dusk:    %s \n' % dusk)

if now_time > datetime.strptime(dawn, '%H:%M:%S'):
    print ('Time is after dawn')
else:
    print ('Time is before dawn')

它返回以下内容:

Traceback (most recent call last):
  File "test.py", line 63, in <module>
    If now_time > datetime.strptime(dawn, '%H:%M:%S'):
TypeError: can't compare datetime.time to datetime.datetime

1 个答案:

答案 0 :(得分:1)

要从time对象中提取datetime对象,请使用datetime.time()函数或datetime.timetz()函数。后者将保留时区信息,而前者则不会。

因此将问题行更改为此:

if now_time > datetime.strptime(dawn, '%H:%M:%S').time():