How to compare two time points in python

爱喝马黛茶的安东尼
Release: 2019-06-22 13:35:50
Original
19717 people have browsed it

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')
Copy after login

Related recommendations: "Python Video Tutorial"

2. Convert datetime to string

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

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
Copy after login

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
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!