Home  >  Article  >  Backend Development  >  python使用datetime模块计算各种时间间隔的方法

python使用datetime模块计算各种时间间隔的方法

WBOY
WBOYOriginal
2016-06-06 11:23:191972browse

本文实例讲述了python使用datetime模块计算各种时间间隔的方法。分享给大家供大家参考。具体分析如下:

python中通过datetime模块可以很方便的计算两个时间的差,datetime的时间差单位可以是天、小时、秒,甚至是微秒,下面的代码就演示了datetime模块在计算时间差时的强大功能

# -*- coding: utf-8 -*-
#!/usr/bin/env python
import datetime
#datetime一般的时间计算
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'相差:%s微秒'%(d1-d2).microseconds
print u'相差:%s秒'%(d1-d2).seconds
print u'相差:%s天'%(d1-d2).days
print u'时间间隔:%s微秒'%d3
#时区转换,当前系统所在时区+1
d = datetime.datetime.now()
d = d + datetime.timedelta(seconds=3600)
print d
print d.ctime()

输出结果如下:

相差:0微秒
相差:67260秒
相差:0天
时间间隔:0:00:00.005000微秒
2013-08-30 11:29:29.663000
Fri Aug 30 11:29:29 2013

希望本文所述对大家的Python程序设计有所帮助。

Statement:
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