美文网首页
字符串与时间之间的转换

字符串与时间之间的转换

作者: simplehu | 来源:发表于2017-10-13 17:06 被阅读0次

    1. 日期输出格式化

    start="2017-09-01 00:00:00"
    date = datetime.datetime.strptime(start,"%Y-%m-%d %H:%M:%S")
    end="2017-10-01 00:00:00"
    date1 = datetime.datetime.strptime(end,"%Y-%m-%d %H:%M:%S")
    

    2、时间比较操作

    在datetime模块中有timedelta类,这个类的对象用于表示一个时间间隔,比如两个日期或者时间的差别
    构造方法:
    datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

    date1-date
    datetime.timedelta(30)
    
    #判断两个日期相差多少天
    (date1-date).days==30  ==》True
    
    #n天后的日期
    now = datetime.datetime.now()
    delta = datetime.timedelta(days=n)
    n_days = now + delta
    print n_days.strftime('%Y-%m-%d %H:%M:%S')
    
    #获取前n天的日期
    now = datetime.datetime.now()
    delta = datetime.timedelta(days=-n)
    n_days = now + delta
    print n_days.strftime('%Y-%m-%d %H:%M:%S')
    

    相关文章

      网友评论

          本文标题:字符串与时间之间的转换

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