zoukankan      html  css  js  c++  java
  • 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 '''
  • 相关阅读:
    简明python_Day2_字典、集合、模块、类、编程习惯
    测试2T2
    测试2T1
    bzoj2761
    一元三次方程求根公式及韦达定理
    状压DP入门——铺砖块
    高精度模板
    测试1T3
    测试1T2
    测试1T1
  • 原文地址:https://www.cnblogs.com/Army-Knife/p/10689615.html
Copyright © 2011-2022 走看看