本文實例講述了python時間日期操作方法。分享給大家供大家參考,具體如下:
#coding=utf-8import timeimport datetimeif __name__ == "__main__": # 今天 now = datetime.datetime.now() print now.strftime('%Y-%m-%d %H:%M:%S') print "%s-%s-%s %s:%s:%s" % (now.year, now.month, now.day, now.hour, now.minute, now.second) print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) # 前一天 now = datetime.datetime.now() dt = now + datetime.timedelta(days=-1) print dt.strftime('%Y-%m-%d %H:%M:%S') print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time() - 24 * 3600)) # 后一天 now = datetime.datetime.now() dt = now + datetime.timedelta(days=1) print dt.strftime('%Y-%m-%d %H:%M:%S') print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time() + 24 * 3600)) # 前一小時 now = datetime.datetime.now() dt = now - datetime.timedelta(hours=1) print dt.strftime("%Y-%m-%d %H:%M:%S") print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time() - 1 * 3600)) # 時間戳 秒 print int(time.time()) # 時間戳 毫秒 print int(round(time.time() * 1000)) # 時間戳 to 日期 print datetime.datetime.fromtimestamp(1507630854) print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(1507630854)) print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) # 日期 to 時間戳 print time.mktime(time.strptime("2017-10-10", "%Y-%m-%d")) print time.mktime(time.strptime("2017-10-10 10:10:10", "%Y-%m-%d %H:%M:%S"))
運行結果:
2020-02-06 11:33:51
2020-2-6 11:33:51
2020-02-06 11:33:51
2020-02-05 11:33:51
2020-02-05 11:33:51
2020-02-07 11:33:51
2020-02-07 11:33:51
2020-02-06 10:33:51
2020-02-06 10:33:51
1580960031
1580960031893
2017-10-10 18:20:54
2017-10-10 18:20:54
2020-02-06 11:33:51
1507564800.0
1507601410.0
PS:這里再為大家推薦幾款關于日期與天數計算的在線工具供大家使用:
在線日期/天數計算器:
http://tools.jb51.net/jisuanqi/date_jisuanqi
在線萬年歷日歷:
http://tools.jb51.net/bianmin/wannianli
在線陰歷/陽歷轉換工具:
http://tools.jb51.net/bianmin/yinli2yangli
Unix時間戳(timestamp)轉換工具:
http://tools.jb51.net/code/unixtime
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python日期與時間操作技巧總結》、《Python數學運算技巧總結》、《Python數據結構與算法教程》、《Python Socket編程技巧總結》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經典教程》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答