Python开发:基于datetime或time模块分别获取当前时间戳方法实例

2019-02-1920:30:58后端程序开发Comments2,424 views字数 1067阅读模式

python的时间模块生成时间戳的方法是非常简单的,因为最近频繁用到了时间戳功能,这里简单总结了一下日常使用最为频繁的两个时间模块各自生成当前时间戳的方法,很简单,具体如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/9632.html

now_time=str(datetime.datetime.now().strftime('%Y%m%d'))
nowTime=str(time.strftime('%Y%m%d',time.localtime(time.time())))
print 'now_time:',now_time
print 'nowTime:',nowTime

结果如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/9632.html

now_time: 20181226
nowTime: 20181226文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/9632.html

上面是生成年月日的时间戳,如果要精确到秒级可以使用下面的方法:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/9632.html

now_time=str(datetime.datetime.now().strftime('%Y%m%d%H%M%S'))
nowTime=str(time.strftime('%Y%m%d%H%M%S',time.localtime(time.time())))
print 'now_time:',now_time
print 'nowTime:',nowTime

结果如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/9632.html

now_time: 20181226091741
nowTime: 20181226091741文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/9632.html

当然想使用不同的分隔符号还可以有下面的形式:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/9632.html

now_time=str(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
nowTime=str(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
print 'now_time:',now_time
print 'nowTime:',nowTime

now_time=str(datetime.datetime.now().strftime('%Y/%m/%d/%H:%M:%S'))
nowTime=str(time.strftime('%Y/%m/%d/%H:%M:%S',time.localtime(time.time())))
print 'now_time:',now_time
print 'nowTime:',nowTime

结果如下:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/9632.html

now_time: 2018-12-26 09:18:58
nowTime: 2018-12-26 09:18:58
now_time: 2018/12/26/09:18:58
nowTime: 2018/12/26/09:18:58文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/9632.html

文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/9632.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/bc/9632.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定