码迷,mamicode.com
首页 > 编程语言 > 详细

python-整理--时间模块

时间:2016-02-18 21:30:24      阅读:246      评论:0      收藏:0      [点我收藏+]

标签:

使用datetime模块处理时间

 1 ###########################################################################
 2 #
 3 #           datetime模块
 4 #
 5 ###########################################################################
 6 
 7 # 导入datetime类,取了别名DateTime(和C#一样的)
 8 from datetime import datetime as DateTime
 9 
10 # 当前时间,按2016-02-05 13:01:01的格式输出
11 print(DateTime.now().strftime(%Y-%m-%d %H:%M:%S))
12 
13 # 当前日期,按2016年02月15格式输出
14 print(DateTime.now().date().strftime(%Y{y}%m{m}%d).format(y=, m=))
15 
16 # 将字符串转为DateTime.第二个参数是字符串的格式,这个格式要匹配进行转换的字符串
17 date=2016/02/23
18 print(type(DateTime.strptime(date,%Y/%m/%d)))
19 print(DateTime.strptime(date,%Y/%m/%d))
20 
21 
22 ## datetime类的一些属性
23 # 最小日期 0001-01-01 00:00:00
24 print(DateTime.min)
25 
26 # 最大日期 9999-12-31 23:59:59.999999
27 print(DateTime.max)
28 
29 # 在比较时间时间隔时,能比较出的时间差别. 0:00:00.000001(1微秒)
30 print(DateTime.resolution)
31 
32 ## datetime对象的一些属性
33 curr=DateTime.now()
34 
35 # 时间区域信息,没有就显示None
36 print(curr.tzinfo)
37 
38 # 年2016 月2 日5 时1 分12 秒23 微秒123456(1000000)
39 print(curr.year)
40 print(curr.month)
41 print(curr.day)
42 print(curr.hour)
43 print(curr.minute)
44 print(curr.second)
45 print(curr.microsecond)
46 
47 
48 ## 时间的操作
49 # 时间差
50 t1=DateTime.strptime(2016-02-05 12:20:00,%Y-%m-%d %H:%M:%S)
51 t2=DateTime.strptime(2016-02-06 12:00:00,%Y-%m-%d %H:%M:%S)
52 
53 # 时间相减的结果是datetime.timedelta类
54 diff=t1-t2
55 
56 # <class ‘datetime.timedelta‘>
57 print(type(diff))
58 
59 # -1 day, 0:20:00
60 print(diff)
61 
62 # 相差天数 相差秒数 相差微秒数
63 print(diff.days) # -1
64 print(diff.seconds) # 1200
65 print(diff.microseconds) # 0
66 
67 # 还有很多属性和方法在python3.4文档上.

 

python-整理--时间模块

标签:

原文地址:http://www.cnblogs.com/mirrortom/p/5199301.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!