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

yipeiwu_com7年前Python基础

本文实例讲述了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程序设计有所帮助。

相关文章

python保存字典和读取字典的实例代码

读取一个已经保存了的字典 f = open('dict_th','r') a = f.read() dict_hi = eval(a) f.close() 保存一个字典 dic...

python实现在windows下操作word的方法

本文实例讲述了python实现在windows下操作word的方法。分享给大家供大家参考。具体实现方法如下: import win32com from win32com.client...

Python+selenium 获取浏览器窗口坐标、句柄的方法

1.0 获取浏览器窗口坐标 python目录可找到Webdriver.py 文件定义了get_window_rect()函数,可获取窗口的坐标和大小(长宽),但出现”Command n...

在python中将字符串转为json对象并取值的方法

如下所示: string =" { "status": "error", "messages": ["Could not find resource or operation '...

Python生成rsa密钥对操作示例

本文实例讲述了Python生成rsa密钥对操作。分享给大家供大家参考,具体如下: # -*- coding: utf-8 -*- import rsa # 先生成一对密钥,然后保存....