Python USES the datetime module to calculate various intervals

  • 2020-04-02 14:43:10
  • OfStack

This article provides an example of how python USES the datetime module to calculate various time intervals. Share with you for your reference. Specific analysis is as follows:

In python, it is very convenient to calculate the difference between two times through the datetime module. The time difference unit of datetime can be days, hours, seconds, or even microseconds. The following code demonstrates the powerful function of the datetime module in calculating the time difference


# -*- coding: utf-8 -*-
#!/usr/bin/env python
import datetime
#datetime General time calculation 
d1 = datetime.datetime(2013, 8, 05,15,50)
d2 = datetime.datetime(2013, 8, 4,21,9,0,0)
d3 = datetime.timedelta(microseconds=5000)
print u' By: %s microseconds '%(d1-d2).microseconds
print u' By: %s seconds '%(d1-d2).seconds
print u' By: %s day '%(d1-d2).days
print u' Time interval: %s microseconds '%d3
# Time zone conversion, the time zone in which the current system is located +1
d = datetime.datetime.now()
d = d + datetime.timedelta(seconds=3600)
print d
print d.ctime()

The output results are as follows:


 By: 0 microseconds 
 By: 67260 seconds 
 By: 0 day 
 Time interval: 0:00:00.005000 microseconds 
2013-08-30 11:29:29.663000
Fri Aug 30 11:29:29 2013

I hope this article has helped you with your Python programming.


Related articles: