您的位置:首页 > 编程语言 > Python开发

python标准库:datetime模块

2018-04-04 17:02 369 查看
原文地址:http://www.bugingcode.com/blog/python_datetime.html

datatime 模块题共用一些处理日期,时间和时间间隔的函数。这个模块使用面向对象的交互取代了time模块中整形/元组类型的时间函数。

在这个模块中的所有类型都是新型类,能够从python中继承和扩展。

这个模块包含如下的类型:

datetime代表了日期和一天的时间

date代表日期,在1到9999之间

time 代表时间和独立日期。

timedelta 代表两个时间或者日期的间隔

tzinfo 实现时区支持

datetime 类型代表了某一个时区的日期和时间,除非有特殊说明,datetime对象使用的是“naive time”,也就是说程序中datetime的时间跟所在的时区有关联。datetime模块提供了一些时区的支持。

datetime

给定一个时间创建datetime对象,可以使用datetime构造函数:

import datetime

now = datetime.datetime(2003, 8, 4, 12, 30, 45)

print now
print repr(now)
print type(now)
print now.year, now.month, now.day
print now.hour, now.minute, now.second
print now.microsecond


结果如下:

$ python datetime-example-1.py
2003-08-04 12:30:45
datetime.datetime(2003, 8, 4, 12, 30, 45)
<type 'datetime.datetime'>
2003 8 4
12 30 45
0


值得注意的是默认字符串代表的是ISO 8601-style时间戳。

你也可以使用内建工厂函数来创建datetime对象(所有的这样的函数提供的是类方法,而不是模块函数)。

import datetime
import time

print datetime.datetime(2003, 8, 4, 21, 41, 43)

print datetime.datetime.today()
print datetime.datetime.now()
print datetime.datetime.fromtimestamp(time.time())

print datetime.datetime.utcnow()
print datetime.datetime.utcfromtimestamp(time.time())


结果如下:

$ python datetime-example-2.py
2003-08-04 21:41:43
2003-08-04 21:41:43.522000
2003-08-04 21:41:43.522000
2003-08-04 21:41:43.522000
2003-08-04 19:41:43.532000
2003-08-04 19:41:43.532000


像在这些例子中,时间对象的默认格式是ISO 8601-style 字符串:“yyyy-mm-dd hh:mm:ss”,毫秒是可选的,可以有也可以没有。

datetime类型提供另一种格式方法,包括高度通用的strftime方法(在time模块中可以看到更加详细的说明)。

import datetime
import time

now = datetime.datetime.now()

print now
print now.ctime()
print now.isoformat()
print now.strftime("%Y%m%dT%H%M%S")
$ python datetime-example-3.py
2003-08-05 21:36:11.590000
Tue Aug  5 21:36:11 2003
2003-08-05T21:36:11.590000
20030805T213611


date和time

date代表着datetime对象中日期部分。

import datetime

d = datetime.date(2003, 7, 29)

print d
print d.year, d.month, d.day

print datetime.date.today()


结果如下:

$ python datetime-example-4.py
2003-07-29
2003 7 29
2003-08-07


time也类似,他代表着时间的一部分,以毫秒级为单位。

import datetime

t = datetime.time(18, 54, 32)

print t
print t.hour, t.minute, t.second, t.microsecond


结果如下:

$ python datetime-example-5.py
18:54:32


datetime提供datetime对象的扩展方法,同时也提供了转换两个对象到一个时间对象上的类方法。

import datetime

now = datetime.datetime.now()

d = now.date()
t = now.time()

print now
print d, t
print datetime.datetime.combine(d, t)


结果如下:

$ python datetime-example-6.py
2003-08-07 23:19:57.926000
2003-08-07 23:19:57.926000
2003-08-07 23:19:57.926000


转载请标明来之:阿猫学编程

更多教程:阿猫学编程-python基础教程
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: