Dry Goods Collection | Python implements time difference calculation

Insert picture description here
Let’s talk about the datetime module in Python today. The datetime module in python can calculate the difference between two times. The unit of time difference of datetime can be days, hours, seconds, or even microseconds. Let’s take a look at the powerful functions of datetime:
from datetime import datetime
a=datetime.now()
b=datetime.now()

a
datetime.datetime(2015, 4, 7, 4, 30, 3, 628556)
b
datetime.datetime(2015, 4, 7, 4, 34, 41, 907292)

str(a)
#Conversion of string, user saves to text or database '2015-04-07 04:30:03.628556'

datetime.strptime(str(a),"%Y-%m-%d %H:%M:%S.%f")
datetime.datetime(2015, 4, 7, 4, 30, 3, 628556)

(b-a)
Out: datetime.timedelta(0, 278, 278736)

(ba).seconds #Calculation of time difference, in seconds
278

Q: How to easily calculate the difference between two times, such as the difference between two times by days, hours, etc.
A: Using the datetime module can easily solve this problem, for example:

import datetime>>> d1 = datetime.datetime(2005, 2, 16)>>> d2 = datetime.datetime(2004, 12, 31)>>> (d1 - d2).days47

The above example demonstrates the calculation of the number of days between two dates.

import datetime
starttime = datetime.datetime.now()
#long running

endtime = datetime.datetime.now()
print (endtime - starttime).seconds

The above example demonstrates an example of calculating the running time, which is displayed in seconds.

d1 = datetime.datetime.now()>>> d3 = d1 + datetime.timedelta(hours=10)>>> d3.ctime()

The above example demonstrates calculating the time 10 hours backward from the current time.
The commonly used classes are: datetime and timedelta. They can be added and subtracted from each other. Each class has some methods and properties to view specific values. For
example, datetime can be viewed: days (day), hours (hour), days of the week (weekday()), etc.; timedelta can be viewed: days (days), seconds Number (seconds) and so on.
Part of the content of the article comes from the Internet, contact intrusion and deletion * The
article reference comes from http://http.taiyangruanjian.com/news/54871.html

Guess you like

Origin blog.csdn.net/zhimaHTTP/article/details/111932598