Home  >  Article  >  Backend Development  >  How to compare two time points in python

How to compare two time points in python

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼Original
2019-06-22 13:35:5019713browse

How to compare two time points in python

How to compare two time points in python? Let me explain the specific steps below:

1. Convert string to datetime

#字符串转datetime
dt = datetime.datetime.strptime('2017-04-19 00:42:44','%Y-%m-%d %H:%M:%S')

Related recommendations: "Python Video Tutorial"

2. Convert datetime to string

#datetime转字符串
str = dt.strftime("%Y-%m-%d-%H")

3.Comparison of datetime

>>> dt1 = datetime.datetime.strptime('2017-04-18 00:40:00','%Y-%m-%d %H:%M:%S')
>>> dt2 = datetime.datetime.strptime('2017-04-18 00:20:00','%Y-%m-%d %H:%M:%S')
>>> print(dt1 - dt2)
0:20:00
>>> print(dt2 - dt1)
-1 day, 23:40:00

It can be seen that when subtracting a larger time from a smaller time, the result is -1 Day, 23:40. Instead of -20 points.

4. Judgment of datetime comparison results

>>> diff = dt2 - dt1
>>> print(diff)
-1 day, 23:40:00
>>> print(diff.days)
-1
>>> print(diff.seconds)
85200

That is, diff.days should be used for comparison. If it is less than 0, the former is smaller.

5. The specific difference in seconds

>>> diff.days * 86400 + diff.seconds
-1200

The above is the detailed content of How to compare two time points in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn