美文网首页
python 日期 datetime

python 日期 datetime

作者: proud2008 | 来源:发表于2020-05-26 11:30 被阅读0次

    datetime与timestamp

    from datetime import datetime
    now = datetime.now()
    print(now)
    #日期转时间戳
    timestamp = now.timestamp()
    print(timestamp,type(timestamp))
    #时间戳转日期
    c2=datetime.fromtimestamp(timestamp)
    print(c2,type(c2))
    ...
    2020-05-22 11:04:35.606201
    1590116675.606201 <class 'float'>
    2020-05-22 11:04:35.606201 <class 'datetime.datetime'>
    
    

    datetime与str

    from datetime import datetime
    # 字符串转日期
    cday = datetime.strptime('2015-6-1 18:19:59', '%Y-%m-%d %H:%M:%S') #
    print(cday)
    print(type(cday))
    # 日期转字符串
    sday=cday.strftime( '%Y-%m-%d %H:%M:%S')
    print(sday)
    print(type(sday))
    ...
    2015-06-01 18:19:59
    <class 'datetime.datetime'>
    2015-06-01 18:19:59
    <class 'str'>
    

    日期加减

    >>> from datetime import datetime, timedelta
    >>> now = datetime.now()
    >>> now
    datetime.datetime(2015, 5, 18, 16, 57, 3, 540997)
    >>> now + timedelta(hours=10)
    datetime.datetime(2015, 5, 19, 2, 57, 3, 540997)
    >>> now - timedelta(days=1)
    datetime.datetime(2015, 5, 17, 16, 57, 3, 540997)
    >>> now + timedelta(days=2, hours=12)
    datetime.datetime(2015, 5, 21, 4, 57, 3, 540997)
    

    相关文章

      网友评论

          本文标题:python 日期 datetime

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