python datatime日期和时间值模块
datetime.time():是一个时间类,这个类接受4个参数,分别代表时,分,秒,毫秒.参数的默认值是为0#!/usr/bin/env python
#coding:utf8
import datetime
t=datetime.time(20, 00, 13, 00)
print t
print '*'*20
print t.hour
print t.minute
print t.second
print t.microsecond
输出结果:
20:00:13
********************
20
0
13
0
datetime.date():是一个日期类,这个类接受3个参数,分别代表年,月,日
today()是这个类的方法,获取当前的日期实例
#!/usr/bin/env python
#coding:utf8
import datetime
t=datetime.date(2014,3,11)
print t
t=datetime.date.today()
print '*'*20
print t
print t.year
print t.month
print t.day
输出结果:
2014-03-11
********************
2014-07-20
2014
7
20
timedeltat日期时间的算术运算
datetime.timedelta():接受7个参数,weeks,days,hours,minutes,seconds.milliseconds,microseconds,默认值为0,这个类只有一个方法total_seconds(),把传入的时间参数值转换成秒数,并返回
#!/usr/bin/env python
#coding:utf8
import datetime
#定义时间周期
time = datetime.timedelta(weeks=1, hours=3, seconds=88)
print time
print time.total_seconds()
输出结果
7 days, 3:01:28
615688.0
日期的算数运算
#!/usr/bin/env python
#coding:utf8
import datetime
today =datetime.date.today()
print today
test_day = datetime.timedelta(weeks=1, days=3, hours=24)
print today - test_day
输出结果:
2014-07-21
2014-07-10
datetime.datetime():时间类和日期类的一个组合,返回的实例包含date和time对象的几乎所有属性(不包含week和millisecond)
#!/usr/bin/env python
#coding:utf8
import datetime
now =datetime.datetime.now()
today =datetime.datetime.today()
utcnow = datetime.datetime.utcnow()
print now
print today
print utcnow
s = ['year','month', 'day', 'hour', 'minute', 'second', 'microsecond']
d = datetime.datetime.now()
for attr in s:
print '%15s: %s'%(attr, getattr(d, attr))
输出结果:
2014-07-21 01:31:34.434000
2014-07-21 01:31:34.434000
2014-07-20 17:31:34.434000
year: 2014
month: 7
day: 21
hour: 1
minute: 31
second: 34
microsecond: 434000
当然日期也可以用来比较和格式化
#!/usr/bin/env python
#coding:utf8
import datetime
t1 = datetime.time(1, 2, 3)
t2 = datetime.time(3, 2, 1)
print t2 < t1
输出结果:
False
格式化的方法
strftime():将时间转换成指定的格式,和time模块里面的用法一样
strptime():将格式化的字符串转化为datetime实例,和time模块里面的用法一样
页:
[1]