In python, The datetime module can be used to conveniently calculate the difference between two time points. The unit of datetime time difference can be days, hours, seconds, or even microseconds, let's take a closer look at the powerful functions of datetime. I wrote something today to calculate the time difference. I remember it was written last year. So I mark it again today to avoid forgetting it.
In [27]: from datetime import datetimeIn [28]: a = datetime. now () In [29]: B = datetime. now () In [32]: aOut [32]: datetime. datetime (2015, 4, 7, 4, 30, 3, 628556) In [33]: bOut [33]: datetime. datetime (2015, 4, 7, 4, 34, 41,907 292) In [34]: str (a) String Conversion, which is stored In text or database Out [34]: '2017-04-07 04:30:03. 628556 'in [35]: datetime. strptime (str (a), "% Y-% m-% d % H: % M: % S. % f ") Out [35]: datetime. datetime (2015, 4, 7, 4, 30, 3, 628556) In [36]: (B-a) Out [36]: datetime. timedelta (0,278,278 736) In [37]: (B-). seconds time difference calculation, in seconds Out [37]: 278
Q: How to easily calculate the difference between the two time periods, such as the time difference between the two days and hours?
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 preceding example shows how to calculate the number of days for two different dates.
import datetimestarttime = datetime.datetime.now()#long runningendtime = datetime.datetime.now()print (endtime - starttime).seconds
The previous example demonstrates the example of calculating the running time, which is displayed in seconds.
>>> d1 = datetime.datetime.now()>>> d3 = d1 + datetime.timedelta(hours=10)>>> d3.ctime()
The previous example shows the 10 hours after calculating the current time.
Common classes include datetime and timedelta. They can be added or subtracted from each other. Each class has some methods and attributes to view specific values, such as datetime: day, hour, and weekday; timedelta can be viewed as days and seconds.
The above is all the content of this article. I hope you will like it.