Python 常用自带 libraries - 日期时间

Python 常用自带 libraries - 日期时间

1 时间 time

1.1 time.struct_time() 时间数据类型

初始化:一般不直接初始化

属性:

  • tm_year, tm_mon 1 ~ 12 之间, tm_mday 1 ~ 31 之间,

  • tm_hour, tm_min, tm_sec, 均在 0 ~ 59 之间

  • tm_wday: 在一星期中星期为第几天,在 0 ~ 6 之间,周一为 0

  • tm_yday: 在一年中为第几天,在 1 ~ 366 之间

  • tm_isdst: 0, 1 或 -1

  • tm_zone: 时区名称的缩写

  • tm_gmtoff: 以秒为单位的UTC以东偏离

1.2 时间的几种表示形式

以下函数,如果不传入参数,则默认以本地时间作为传入

  • time.time(): -> float;local time

  • time.time_nc(): -> int;nanoseconds (= 1e9 seconds);local time

  • time.gmtime(secs): float -> time.struct_time;默认为(不传入参数)当前的 UTC time

  • time.localtime(secs): float -> time.struct_time;默认为(不传入参数)当前的 local time

    传入相同的 secs,time.localtime(secs) 与 time.gmtime(secs) 始终存在时区时间差。

不同表示形式之间的转换

  • time.ctime(secs): float -> str;默认为(不传入参数)当前的 local time

    • Sat Feb 12 19:42:52 2022

    • 等价于 time.asctime(time.localtime(secs))

  • time.asctime(t): time.struct_time -> str

  • time.mktime(t): time.struct_time -> float;默认为(不传入参数)当前的 local time

    • 相当于 time.ctime() 的逆函数

测试实例

import time
print('time:', time.time(), '[type]:', type(time.time()))
print('time_ns:', time.time_ns(), '[type]:', type(time.time_ns()), time.time_ns() * 1e-9)
print('gmtime:', time.gmtime(), '[type]:', type(time.gmtime()))
print('localtime:', time.localtime(), '[type]:', type(time.localtime()))
print('ctime:', time.ctime(), '[type]:', type(time.ctime()))
print('asctime:', time.asctime(), '[type]:', type(time.asctime()))

1.3 统计程序运行时间

以下 3 个函数均返回为 float 类型,单位为 second

  • time.time():系统时间,如果在两次调用之间,将系统时间回调,会导致第二次调用的时间小于第一次

  • time.perf_counter()一般用此函数测试程序运行时间,包括 time.sleep() 的时间

  • time.process_time():不包括 time.sleep() 的时间

与之对应的 3 个 nanoseconds 函数,返回为 int 类型

  • time.time_ns(), time.perf_counter_ns(), time.process_time_ns()

测试实例

import time
t1, t2, t3 = time.time(), time.perf_counter(), time.process_time()
[1.**1. for i in range(int(1e6))]
time.sleep(2.)
print('time:', time.time() - t1)
print('perf_counter:', time.perf_counter() - t2)
print('process_time:', time.process_time() - t3)
# output
# time: 2.070873260498047
# perf_counter: 2.0581983
# process_time: 0.0625

1.4 time.strptime()time.strftime()

  • time.strptime(str[, format]):返回 time.struct_time 类型;将字符串(依据format)解析为 time.struct_time 时间

  • time.strftime(format[, t]):返回 str 类型;将 time.struct_time 时间按指定的 format 转换为字符串

注意:与 datetime.strftime() 不同的是,time.strftime() 未提供 %f (millisecond)的格式

参考资料

[1] Python time.strftime() 方法, RUNOOM, 地址

2. 日期 date

to be completed...

3. 日期时间 datetime

3.1 数据类型

  • datetime.datetime()

    • 初始化:datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)

    • 属性:year, month, day, hour, minute, second, microsecond, 和 tzinfo

    • datetime.datetime() 运算:两个 datetime() 实例之差为 timedelta()实例,两个 datetime() 实例无法相加。

  • datetime.timedelta()

    • 用于时间的加减,如计算某个时刻(datetime() 实例)多长时间(timedelta() 实例)之后/之前的时刻

    • 初始化:datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

    • 属性:days, seconds, 和 microseconds

    • 方法:timedelta.total_seconds() 返回总秒数

3.2 常用函数

  • datetime.fromtimestamp(timestamp, tz=None): float -> datetime.datetime; 根据时间戳(timestamp)建立 datetime.datetime()

    • timestamp:单位为 second
  • 获取当前日期时间

    • datetime.datetime.now() 当地时间(Local Time)

    • datetime.datetime.utcnow() UTC时间

    • datetime.datetime.today()

      等价于 datetime.fromtimestamp(time.time())

    均返回 datetime.datetime()

datatime() 实例格式化输出方法

  • datetime.strftime() 方法,格式化 datatime() 实例

    • 自定义输出日期时间的格式

    • 返回 str 类型

    • 传入字符串格式定义 地址

  • datetime.isoformat(sep='T', timespec='auto') 方法

    • ISO 标准格式化时间

    • 返回 str 类型

    • 参数 sep:日期与时间之间的分隔符

    • 参数 timespec:以下字符串类型:

      • 'auto': 如果 microsecond 为 0 则与 'seconds' 相同,否则与 'microseconds' 相同。

      • 'hours': 以两位数的 HH 格式 包含 hour。

      • 'minutes': 以 HH:MM 格式包含 hour 和 minute。

      • 'seconds': 以 HH:MM:SS 格式包含 hour, minute 和 second。

      • 'milliseconds': 包含完整时间,但将秒值的小数部分截断至微秒。 格式为 HH:MM:SS.sss

      • 'microseconds': 以 HH:MM:SS.ffffff 格式包含完整时间。

测试例子

import datetime
t = datetime.datetime.now()  # datetime.datetime() 类型
print(t.isoformat(sep=' ', timespec='milliseconds'))  # str 类型
print(t.strftime('%Y-%m-%d %H:%M:%S.%f'))  # str 类型
# output: 2022-02-12 18:48:47.632
# output: 2022-02-12 18:48:47.632679
# 可以看出 isoformat() 是截断到3位数字而不是四舍五入

实用例子

1. 将 second 转换为 HH:MM:SS.FFF 的格式

import datetime
# seconds 不能超过 1 day,否者 hour 会从 0 开始计数
# milliseconds 超出的小数会直接舍去
def Secs2Time(secs=0):
    # secs: seconds
    if secs >= 86400: # secs 不能超过一天
      return None
    dt = datetime.datetime.fromtimestamp(secs, datetime.timezone.utc)
    # 设置为 UTC 时区,从 00:00:00 开始
    s = dt.strftime('%H:%M:%S.%f')[:-3]
    return s

等价于如下函数:

import datetime
# seconds 超过 1 day 会记录在 hour 中 (hour > 24)
# milliseconds 超出的小数会四舍五入
def Secs2Time2(secs):
    # secs: seconds
    sec = int(secs) # 整数部分
    ms = round(1000 * (secs - int(secs)))  # 小数部分
    m, s = divmod(sec, 60)
    h, m = divmod(m, 60)
    time_str = '{0:0>2d}:{1:0>2d}:{2:0>2d}.{3:0>3d}'.format(h, m, s, ms)
    return time_str
posted @ 2022-02-12 21:39  veager  阅读(75)  评论(0编辑  收藏  举报