Today I wrote something to calculate the time difference, I remember writing it last year, so mark again today, lest I forget
in [+]: from datetime import Datetimein [+]: A=datetime.now () in []: B=datetime.now () in [+]: aout[32]: Datetime.dateti Me (4, 7, 4, 3, 628556) in [Max]: bout[33]: Datetime.datetime (4, 7, 4,,, 907292) in [+]: Str (a) string Conversion, user stored to text or database out[34]: ' 2015-04-07 04:30:03.628556 ' in []:d atetime.strptime (str (a), "%y-%m-%d%h:%m:%s.%f") out[ :d Atetime.datetime (4, 7, 4, 3, 628556) in []: (B-A) out[36]: Datetime.timedelta (0, 278, 278736) in [PNS]: (b-a) Seconds Calculation of the time difference in seconds out[37]: 278
Q: How to conveniently calculate the difference of two time, such as two time difference a few days, a few hours, etc.
A: Using the DateTime module can easily solve this problem, for example:
>>> import datetime>>> D1 = Datetime.datetime (2005, 2, +) >>> D2 = Datetime.datetime (2004, 12, ) >>> (D1-D2). days47
The previous example shows a calculation that calculates a two-day difference between days.
Import datetimestarttime = Datetime.datetime.now () #long runningendtime = Datetime.datetime.now () print (Endtime- starttime). Seconds
The example above shows the calculation run time, which is displayed in seconds.
>>> D1 = Datetime.datetime.now () >>> d3 = d1 + Datetime.timedelta (hours=10) >>> d3.ctime ()
The previous example shows the time to calculate the current time backwards by 10 hours.
The classes used in this book are: DateTime and Timedelta two. They can be added and reduced between each other. Each class has some methods and properties to view specific values, such as DateTime can be viewed: Days, hours (hour), Day of the Week (weekday ()), etc. timedelta can view: days, seconds (seconds), etc.
The above mentioned is the whole content of this article, I hope you can like.