zoukankan      html  css  js  c++  java
  • 【python】 time模块和datetime模块详解 【转】

    一、time模块

     time模块中时间表现的格式主要有三种:

      a、timestamp时间戳,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量

      b、struct_time时间元组,共有九个元素组。

      c、format time 格式化时间,已格式化的结构使时间更具可读性。包括自定义格式和固定格式。

    1、时间格式转换图:

    2、主要time生成方法和time格式转换方法实例:

     1 import time
     2 
     3 #【生成timestamp时间戳】
     4 print(time.time())
     5 print(time.mktime(time.localtime())) #struct_time to timestamp
     6 print('-'*20)
     7 
     8 # 【生成struct_time时间元组】
     9 # timestamp to struct_time 【本地时间】
    10 print(time.localtime())
    11 print(time.localtime(time.time()))
    12 print('-'*20)
    13 # timestamp to struct_time 【格林威治时间】
    14 print(time.gmtime())
    15 print(time.gmtime(time.time()))
    16 print('-'*20)
    17 #format_time(格式化时间) to struct_time(时间元组)
    18 print(time.strptime('2014-11-11', '%Y-%m-%d'))
    19 print(time.strptime('2011-05-05 16:37:06', '%Y-%m-%d %X'))
    20 print('-'*20)

    struct_time元组元素结构

    属性                            值
    tm_year(年)                  比如2011 
    tm_mon(月)                   1 - 12
    tm_mday(日)                  1 - 31
    tm_hour(时)                  0 - 23
    tm_min(分)                   0 - 59
    tm_sec(秒)                   0 - 61
    tm_wday(weekday)             0 - 6(0表示周日)
    tm_yday(一年中的第几天)        1 - 366
    tm_isdst(是否是夏令时)        默认为-1

    format time结构化表示

    格式 含义
    %a 本地(locale)简化星期名称
    %A 本地完整星期名称
    %b 本地简化月份名称
    %B 本地完整月份名称
    %c 本地相应的日期和时间表示
    %d 一个月中的第几天(01 - 31)
    %H 一天中的第几个小时(24小时制,00 - 23)
    %I 第几个小时(12小时制,01 - 12)
    %j 一年中的第几天(001 - 366)
    %m 月份(01 - 12)
    %M 分钟数(00 - 59)
    %p 本地am或者pm的相应符
    %S 秒(01 - 61)
    %U 一年中的星期数。(00 - 53星期天是一个星期的开始。)第一个星期天之前的所有天数都放在第0周。
    %w 一个星期中的第几天(0 - 6,0是星期天)
    %W 和%U基本相同,不同的是%W以星期一为一个星期的开始。
    %x 本地相应日期
    %X 本地相应时间
    %y 去掉世纪的年份(00 - 99)
    %Y 完整的年份
    %Z 时区的名字(如果不存在为空字符)
    %% ‘%’字符

    常见结构化时间组合:

    print time.strftime("%Y-%m-%d %X")
    #2018-9-5 14:50:13

     3、time加减

    1 #timestamp加减单位以秒为单位
    2 import time
    3 t1 = time.time()
    4 t2=t1+10
    5 
    6 print time.ctime(t1)#Wed Oct 26 21:15:30 2018
    7 print time.ctime(t2)

    二、datetime模块

    datatime模块重新封装了time模块,提供更多接口,提供的类有:date,time,datetime,timedelta,tzinfo。

    1、date类

     1 from  datetime import *
     2 import time
     3 # 【静态方法和字段】
     4 print(date.max) #对象所能表示的最大、最小日期
     5 print(date.min)
     6 print(date.resolution)#对象表示日期的最小单位。这里是天
     7 print(date.today()) #返回一个表示当前本地日期的date对象
     8 print(date.fromtimestamp(time.time())) #根据给定的时间戮,返回一个date对象;
     9 
    10 # 【方法和属性】
    11 now = date(2018, 9, 5)
    12 tomorrow = now.replace(day = 27)
    13 
    14 print(now.replace(2012,8,8)) #生成一个新的日期对象,用参数指定的年,月,日代替原有对象中的属性。
    15 print(now,tomorrow)
    16 print('-'*20)
    17 
    18 print(now.timetuple()) #返回日期对应的time.struct_time对象;
    19 print('-'*20)
    20 
    21 print(now.weekday()) #返回weekday,如果是星期一,返回0;如果是星期2,返回1,以此类推;
    22 print(now.isoweekday()) #返回weekday,如果是星期一,返回1;如果是星期2,返回2,以此类推;
    23 print('-'*20)
    24 
    25 print(now.isocalendar()) #返回格式如(year,month,day)的元组;
    26 print(now.isoformat()) #返回格式如'YYYY-MM-DD’的字符串;
    27 print(now.strftime("%Y-%m-%d"))

    2、time类

    1 from  datetime import *
    2 tm = time(23,46,10)
    3 print(tm)
    4 print('hour: %d, minute: %d, second: %d, microsecond: %d' % (tm.hour, tm.minute, tm.second, tm.microsecond))
    5 tm1 = tm.replace(hour=20)
    6 print('tm1:', tm1)
    7 print('isoformat:', tm.isoformat())
    8 print('strftime', tm.strftime("%X"))

    3、datetime类

     1 # 静态方法和字段
     2 from  datetime import *
     3 import time
     4 
     5 print('datetime.max:', datetime.max)
     6 print('datetime.min:', datetime.min)
     7 print('datetime.resolution:', datetime.resolution)
     8 print('-'*20)
     9 print('today():', datetime.today())
    10 print('now():', datetime.now())
    11 print('utcnow():', datetime.utcnow())
    12 print('-'*20)
    13 print('fromtimestamp(tmstmp):', datetime.fromtimestamp(time.time()))
    14 print('utcfromtimestamp(tmstmp):', datetime.utcfromtimestamp(time.time()))
    15 
    16 # 方法和属性
    17 dt=datetime.now()#datetime对象
    18 print(dt.date())
    19 print(dt.time())
    20 print(dt.replace())
    21 print('-'*20)
    22 print(dt.timetuple())
    23 print(dt.utctimetuple())
    24 print('-'*20)
    25 print(dt.toordinal())
    26 print(dt.weekday())
    27 print('-'*20)
    28 print(dt.isocalendar())
    29 print(dt.ctime())
    30 print(dt.strftime)

    4.timedelta类,时间加减

     1 from  datetime import *
     2 
     3 dt = datetime.now()
     4 
     5 dt1 = dt + timedelta(days=-1)#昨天
     6 dt2 = dt - timedelta(days=1)#昨天
     7 dt3 = dt + timedelta(days=1)#明天
     8 delta_obj = dt3-dt1
     9 
    10 print(type(delta_obj),delta_obj)
    11 print(delta_obj.days,delta_obj.total_seconds())

     5、tzinfo时区类

     1 from datetime import datetime, tzinfo,timedelta
     2 
     3 """
     4 tzinfo是关于时区信息的类
     5 tzinfo是一个抽象类,所以不能直接被实例化
     6 """
     7 class UTC(tzinfo):
     8     def __init__(self,offset = 0):
     9         self._offset = offset
    10 
    11     def utcoffset(self, dt):
    12         return timedelta(hours=self._offset)
    13 
    14     def tzname(self, dt):
    15         return "UTC +%s" % self._offset
    16 
    17     def dst(self, dt):
    18         return timedelta(hours=self._offset)
    19 
    20 #北京时间
    21 beijing = datetime(2011,11,11,0,0,0,tzinfo = UTC(8))
    22 print ("beijing time:",beijing)
    23 #曼谷时间
    24 bangkok = datetime(2011,11,11,0,0,0,tzinfo = UTC(7))
    25 print ("bangkok time",bangkok)
    26 #北京时间转成曼谷时间
    27 print ("beijing-time to bangkok-time:",beijing.astimezone(UTC(7)))
    28 
    29 #计算时间差时也会考虑时区的问题
    30 timespan = beijing - bangkok
    31 print ("时差:",timespan)
  • 相关阅读:
    1002. Find Common Characters查找常用字符
    338. Counting Bits_比特位计数_简单动态规划
    Rail_UVa514_栈
    784. Letter Case Permutation C++字母大小写全排列
    C语言实现哈夫曼编码(最小堆,二叉树)
    559. Maximum Depth of N-ary Tree C++N叉树的最大深度
    27. Remove Element C++移除元素
    26. Remove Duplicates from Sorted Array C++ 删除排序数组中的重复项
    linux软件源配置
    linux 下安装 maven
  • 原文地址:https://www.cnblogs.com/louis-w/p/9591747.html
Copyright © 2011-2022 走看看