Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

datetime - how to get compare time values and difference in python

i have 3 character type columns in my table has time format values i.e

while processing (in python 3.7) to in if condition i am using following statement;

t1 = '09:12' 
t2 = '09:10'
t3 = '20:00'

if datetime.strptime(t1, '%H:%M') > datetime.strptime(t2, '%H:%M'):
    print((datetime.strptime(t1, '%H:%M') - datetime.strptime(t2, '%H:%M')))
    # above prints 00:02 but i need it to be 00:12 but below statement raise error
    print((datetime.strptime(t1, '%H:%M') - datetime.strptime(t2, '%H:%M'))) + datetime.strptime(t2, '%M')

i need to ask

a) am i doing right thing to get compare above time values (string to date) or i have to compare it with strings values

b) i require difference of above subtract value with 00:12, please assist.

question from:https://stackoverflow.com/questions/65679863/how-to-get-compare-time-values-and-difference-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

what about flooring t2's minute?

from datetime import datetime

t1 = '09:12' 
t2 = '09:10'

if datetime.strptime(t1, '%H:%M') > datetime.strptime(t2, '%H:%M'):
    print(datetime.strptime(t1, '%H:%M') - datetime.strptime(t2, '%H:%M').replace(minute=0))
    
# 0:12:00

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...