Python 将时间戳转换为日期

时间戳转为日期

  • time模块,使用localtime转换,再使用strftime格式化

    import time
    
    timestamp = 1609834156
    date = time.localtime(timestamp)
    format_date = time.strftime('%Y-%m-%d %H:%M:%S', date)
    print(format_date)
    

    输出:2021-01-05 16:09:16

  • datetime模块,使用datetime.fromtimestamp转换,再使用strftime格式化

    import datetime
    
    timestamp = 1609834156
    date = datetime.datetime.fromtimestamp(timestamp)
    format_date = date.strftime('%Y-%m-%d %H:%M:%S')
    print(format_date)
    

    输出:2021-01-05 16:09:16

posted @ 2022-04-07 11:16  王舰  阅读(1792)  评论(0编辑  收藏  举报