网络编程
位置:首页>> 网络编程>> Python编程>> python时间日期操作方法实例小结

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

作者:李琼涛  发布时间:2021-03-13 11:01:45 

标签: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.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程序设计有所帮助。

来源:https://my.oschina.net/qiongtaoli/blog/1548739

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com