仅比较日期时间中的时间部分 - Python

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15105112/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:20:33  来源:igfitidea点击:

Compare only time part in datetime - Python

pythondatetimepython-2.x

提问by Amit K.

I want to compare only time part in datetime. I have different dates with only time field to compare. Since dates are different and only time part i want to consider So i think creating two datetime object will not help. my string as

我只想比较日期时间中的时间部分。我有不同的日期,只有时间字段可以比较。由于日期不同并且我只想考虑时间部分所以我认为创建两个 datetime 对象将无济于事。我的字符串作为

start="22:00:00"
End="03:00:00"
Tocompare="23:30:00"

Above are strings when i convert them with datetime as

以上是我将日期时间转换为字符串时的字符串

dt=datetime.strptime(start,"%H:%M:%S")

it gives

它给

1900-01-01 22:00:00

which is default date in python. So i need to avoid all this and want only time part. I simply need to check does my Tocomparefalls between startand End

这是python中的默认日期。所以我需要避免这一切,只想要时间部分。我只需要检查我是否Tocompare落在startEnd

回答by jarmod

Compare their times using datetime.time().

使用datetime.time()比较它们的时间。

回答by Yueyoum

import datetime

start = datetime.datetime.strptime(start, '%H:%M:%S')
start = datetime.time(start.hour, start.minute,start.second)

tocompare = datetime.datetime.strptime(tocompare, '%H:%M:%S')
tocompare = datetime.time(tocompare.hour, tocompare.minute, tocompare.second)

start > tocompare # False

回答by matt

Just call the .time()methodof the datetimeobjects to get their hours, minutes, seconds and microseconds.

只需调用.time()方法的的datetime对象,以得到他们的小时,分钟,秒和毫秒。

dt = datetime.strptime(start,"%H:%M:%S").time()