• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

python时间日期操作方法实例小结

python 搞代码 4年前 (2022-01-07) 27次浏览 已收录 0个评论

这篇文章主要介绍了python时间日期操作方法,结合实例形式总结分析了Python针对日期时间的转换、计算相关操作技巧,需要的朋友可以参考下

本文实例讲述了python时间日期操作方法。分享给大家供大家参考,具体如下:

 #coding=utf-8 import time import datetime if __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.fromtime<a style="color:transparent">来源gao($daima.com搞@代@#码网</a>stamp(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.gaodaima.com/jisuanqi/date_jisuanqi

在线万年历日历:
http://tools.gaodaima.com/bianmin/wannianli

在线阴历/阳历转换工具:
http://tools.gaodaima.com/bianmin/yinli2yangli

Unix时间戳(timestamp)转换工具:
http://tools.gaodaima.com/code/unixtime

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python日期与时间操作技巧总结》、《Python数学运算技巧总结》、《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》

希望本文所述对大家Python程序设计有所帮助。

以上就是python时间日期操作方法实例小结的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python时间日期操作方法实例小结

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址