python3 datetime和time获取当前日期和时间

 1 import datetime
 2 import time
 3  
 4 # 获取当前时间, 其中中包含了year, month, hour, 需要import datetime
 5 today = datetime.date.today()
 6 print(today)
 7 print(today.year)
 8 print(today.month)
 9 print(today.day)
10 '''
11 >>>2017-01-01
12 >>>2017
13 >>>1
14 >>>1
15 '''
16  
17  
18 # 获得明天, 其他依次类推
19 tomorrow = today + datetime.timedelta(days=1)
20 print(tomorrow)
21 '''
22 >>>2017-01-02
23 '''
24  
25  
26 # 时间相减,相加同理
27 now = datetime.timedelta(days=0, hours=0, minutes=3, seconds=50);
28 pre = datetime.timedelta(days=0, hours=0, minutes=1, seconds=10);
29  
30 duration_sec = (now - pre).seconds
31 duration_day = (now - pre).days
32 print(type(duration_sec))
33 print(type(now - pre))
34 print(duration_sec)
35 print(duration_day)
36 '''
37 >>><class 'int'>
38 >>><class 'datetime.timedelta'>
39 >>>160
40 >>>0
41 '''
42  
43  
44 # 使用time.strftime(format, p_tuple)获取当前时间,需要import time
45 now = time.strftime("%H:%M:%S")
46 print(now)
47 '''
48 >>>23:49:34
49 '''
50  
51 # 使用datetime.now()
52 now = datetime.datetime.now()
53 print(now)
54 print(now.year)
55 print(now.month)
56 print(now.day)
57 print(now.hour)
58 print(now.minute)
59 print(now.second)
60 print(now.microsecond)
61 '''
62 >>>2017-01-01 23:49:34.789292
63 >>>2017
64 >>>1
65 >>>1
66 >>>23
67 >>>49
68 >>>34
69 >>>789292
70 '''

 

转载于:https://www.cnblogs.com/Army-Knife/p/10689615.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值