不灭的焱

革命尚未成功,同志仍须努力下载JDK17

作者:Albert.Wen  添加时间:2021-05-05 17:57:00  修改时间:2024-04-13 15:53:19  分类:Python基础  编辑

之前不太理解ISO8601时间格式,后来看了下网上文章,其实是没有固定的单一格式。

按照下面这些其实都属于ISO8601时间格式:

2019-03-25T16:00:00.000111Z
2019-03-25T16:00:00.111Z
2019-03-25T16:00:00Z
2019-03-25T16:00:00
...

Z表示祖鲁时间Zulu time 即+0时区,若去掉不写Z则采用系统本地时区。

ISO8601时间还有很多其他扩展格式。

下面代码处理的也就是普通格式

 【Python相关函数】

def datetime_iso_to_utc(time_str, fmt='%Y-%m-%dT%H:%M:%S.%fZ', timespec='seconds'):
    """
    ISO8601时间转换为时间戳
    :param time_str: iso时间字符串 2019-03-25T16:00:00.000Z,2019-03-25T16:00:00.000111Z
    :param fmt: %Y-%m-%dT%H:%M:%S.%fZ,其中%f 表示毫秒或者微秒
    :param timespec: 返回时间戳最小单位 seconds 秒,milliseconds 毫秒,microseconds 微秒
    :return: 时间戳 默认单位秒
    """
    tz = pytz.timezone('Asia/Shanghai')
    utc_time = datetime.strptime(time_str, fmt)  # 将字符串读取为 时间 class datetime.datetime

    time_obj = utc_time.replace(tzinfo=pytz.utc).astimezone(tz)

    times = {
        'seconds': int(time_obj.timestamp()),
        'milliseconds': round(time_obj.timestamp() * 1000),
        'microseconds': round(time_obj.timestamp() * 1000 * 1000),
    }

    return times[timespec]


def datetime_utc_to_iso(time_utc, fmt='%Y-%m-%dT%H:%M:%S.%fZ'):
    """
    时间戳转换到ISO8601标准时间(支持微秒级输出 YYYY-MM-DD HH:MM:SS.mmmmmm)
    :param time_utc: 时间戳,支持 秒,毫秒,微秒级别
    :param fmt: 输出的时间格式  默认 iso=%Y-%m-%dT%H:%M:%S.%fZ;其中%f表示微秒6位长度
    此函数特殊处理,毫秒/微秒部分 让其支持该部分的字符格式输出
    :return:
    """
    fmt = fmt.replace('%f', '{-FF-}')  # 订单处理微秒数据 %f
    length = min(16, len(str(time_utc)))  # 最多去到微秒级

    # 获取毫秒/微秒 数据
    sec = '0'
    if length != 10:  # 非秒级
        sec = str(time_utc)[:16][-(length - 10):]  # 最长截取16位长度 再取最后毫秒/微秒数据
    sec = '{:0<6}'.format(sec)  # 长度位6,靠左剩下的用0补齐
    time_utc = float(str(time_utc)[:10])  # 转换为秒级时间戳

    return datetime.utcfromtimestamp(time_utc).strftime(fmt).replace('{-FF-}', sec)

 

 

参考:

https://en.wikipedia.org/wiki/ISO_8601

https://docs.Python.org/zh-cn/3.7/library/datetime.html?highlight=isoformat#strftime-strptime-behavior

https://www.w3.org/TR/NOTE-datetime

https://www.cryptosys.net/pki/manpki/pki_iso8601datetime.html

https://www.hhtjim.com/string-to-a-timestamp-iso8601-time-processing.html