time和datetime的区别

time
在 Python 文档里,time是归类在Generic Operating System Services中,换句话说, 它提供的功能是更加接近于操作系统层面的。通读文档可知,time 模块是围绕着 Unix Timestamp 进行的。

该模块主要包括一个类 struct_time,另外其他几个函数及相关常量。 需要注意的是在该模块中的大多数函数是调用了所在平台C library的同名函数, 所以要特别注意有些函数是平台相关的,可能会在不同的平台有不同的效果。另外一点是,由于是基于Unix Timestamp,所以其所能表述的日期范围被限定在 1970 - 2038 之间,如果你写的代码需要处理在前面所述范围之外的日期,那可能需要考虑使用datetime模块更好

def strtotimestamp(str=None,format='%Y-%m-%d'):
    if str:
        tp = time.strptime(str,format())  #Parse a string to a time tuple according to a format specification.
        res = time.mktime(tp)
        #Convert a time tuple in local time to seconds since the Epoch(1970-01-01 00:00:00 UTC)
        #时间元组转换为时间戳
    else:
        res = time.time() #Return the current time in seconds since the Epoch获取当前时间戳
        #不做处理,时间戳为 float 类型
    return int(res)

 

datetime
datetime 比 time 高级了不少,可以理解为 datetime 基于 time 进行了封装,提供了更多实用的函数。在datetime 模块中包含了几个类,具体关系如下:

object

    • timedelta  # 主要用于计算时间跨度
    • tzinfo         # 时区相关
    • time          # 只关注时间
    • date          # 只关注日期
    • datetime  # 同时有时间和日期
posted @ 2018-06-13 18:19  liuyanerfly  阅读(6130)  评论(0编辑  收藏  举报