python datatime模块_python datatime日期和时间值模块

datetime.time():是一个时间类,这个类接受4个参数,分别代表时,分,秒,毫秒.参数的默认值是为0

1 #!/usr/bin/env python

2 #coding:utf8

3 importdatetime4 t=datetime.time(20, 00, 13, 00)5 printt6 print '*'*20

7 printt.hour8 printt.minute9 printt.second10 printt.microsecond11

12 输出结果:13 20:00:13

14 ********************

15 20

16 017 13

18 0

View Code

datetime.date():是一个日期类,这个类接受3个参数,分别代表年,月,日

today()是这个类的方法,获取当前的日期实例

1 #!/usr/bin/env python

2 #coding:utf8

3 importdatetime4 t=datetime.date(2014,3,11)5 printt6 t=datetime.date.today()7 print '*'*20

8 printt9 printt.year10 printt.month11 printt.day12

13 输出结果:14 2014-03-11

15 ********************

16 2014-07-20

17 2014

18 7

19 20

View Code

timedeltat日期时间的算术运算

datetime.timedelta():接受7个参数,weeks,days,hours,minutes,seconds.milliseconds,microseconds,默认值为0,这个类只有一个方法total_seconds(),把传入的时间参数值转换成秒数,并返回

1 #!/usr/bin/env python

2 #coding:utf8

3 importdatetime4 #定义时间周期

5 time = datetime.timedelta(weeks=1, hours=3, seconds=88)6 printtime7 printtime.total_seconds()8

9 输出结果10 7 days, 3:01:28

11 615688.0

View Code

日期的算数运算

1 #!/usr/bin/env python

2 #coding:utf8

3 importdatetime4 today =datetime.date.today()5 printtoday6 test_day = datetime.timedelta(weeks=1, days=3, hours=24)7 print today -test_day8

9 输出结果:10 2014-07-21

11 2014-07-10

View Code

datetime.datetime():时间类和日期类的一个组合,返回的实例包含date和time对象的几乎所有属性(不包含week和millisecond)

1 #!/usr/bin/env python

2 #coding:utf8

3 importdatetime4 now =datetime.datetime.now()5 today =datetime.datetime.today()6 utcnow =datetime.datetime.utcnow()7

8 printnow9 printtoday10 printutcnow11

12

13 s = ['year','month', 'day', 'hour', 'minute', 'second', 'microsecond']14

15 d =datetime.datetime.now()16 for attr ins:17 print '%15s: %s'%(attr, getattr(d, attr))18

19 输出结果:20 2014-07-21 01:31:34.434000

21 2014-07-21 01:31:34.434000

22 2014-07-20 17:31:34.434000

23 year: 2014

24 month: 7

25 day: 21

26 hour: 1

27 minute: 31

28 second: 34

29 microsecond: 434000

View Code

当然日期也可以用来比较和格式化

1 #!/usr/bin/env python

2 #coding:utf8

3 importdatetime4 t1 = datetime.time(1, 2, 3)5 t2 = datetime.time(3, 2, 1)6

7 print t2

9 输出结果:10 False

View Code

格式化的方法

strftime():将时间转换成指定的格式,和time模块里面的用法一样

strptime():将格式化的字符串转化为datetime实例,和time模块里面的用法一样

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值