美文网首页python-docx
python 时间转换

python 时间转换

作者: leyu | 来源:发表于2016-12-25 14:23 被阅读0次

    时间格式有字符串、时间数组、时间戳,用到的主要datetime和time

    Paste_Image.png

    1.字符串转换成datetime、时间数组

    >>> import datetime,time
    >>> t1 = '2016-12-25 10:59:12'
    >>> t2=datetime.datetime.strptime(t1,'%Y-%m-%d %H:%M:%S') #datetime格式
    >>> t2
    datetime.datetime(2016, 12, 25, 10, 59, 12)
    >>> t3=time.strptime(t1,'%Y-%m-%d %H:%M:%S') #时间数组格式
    >>> t3
    time.struct_time(tm_year=2016, tm_mon=12, tm_mday=25, tm_hour=10, tm_min=59, tm_sec=12, tm_wday=6, tm_yday=360, tm_isdst=-1)
    
    1. datetime、时间数组转换为字符串
    >>> t2=datetime.datetime.strptime(t1,'%Y-%m-%d %H:%M:%S')
    >>> t2
    datetime.datetime(2016, 12, 25, 10, 59, 12)
    >>> t2.strftime('%Y-%m-%d %H:%M:%S')
    '2016-12-25 10:59:12'
    >>> time.strftime('%Y-%m-%d %H:%M:%S',t3)
    '2016-12-25 10:59:12'
    

    3.时间数组转换为时间戳

    >>> t3
    time.struct_time(tm_year=2016, tm_mon=12, tm_mday=25, tm_hour=10, tm_min=59, tm_sec=12, tm_wday=6, tm_yday=360, tm_isdst=-1)
    >>> int(time.mktime(t3))
    1482634752
    

    4.时间戳转换为时间数组

    >>> t3_timestamp = time.mktime(t3)
    >>> time.localtime(t3_timestamp)
    time.struct_time(tm_year=2016, tm_mon=12, tm_mday=25, tm_hour=10, tm_min=59, tm_sec=12, tm_wday=6, tm_yday=360, tm_isdst=0)
    

    5.时间戳转换为字符串

    >>> t3_timestamp
    1482634752.0
    >>> time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(t3_timestamp))
    '2016-12-25 10:59:12'
    

    6.字符串转换为时间戳

    >>> t1
    '2016-12-25 10:59:12'
    >>> time.mktime(time.strptime(t1,'%Y-%m-%d %H:%M:%S'))
    1482634752.0
    

    相关文章

      网友评论

        本文标题:python 时间转换

        本文链接:https://www.haomeiwen.com/subject/gawrvttx.html