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

yipeiwu_com6年前Python基础

python的时间模块生成时间戳的方法是非常简单的,因为最近频繁用到了时间戳功能,这里简单总结了一下日常使用最为频繁的两个时间模块各自生成当前时间戳的方法,很简单,具体如下:

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

结果如下:

now_time: 20181226
nowTime: 20181226

上面是生成年月日的时间戳,如果要精确到秒级可以使用下面的方法:

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: 20181226091741
nowTime: 20181226091741

当然想使用不同的分隔符号还可以有下面的形式:

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

结果如下:

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

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对【听图阁-专注于Python设计】的支持。如果你想了解更多相关内容请查看下面相关链接

相关文章

Python 70行代码实现简单算式计算器解析

描述:用户输入一系列算式字符串,程序返回计算结果。 要求:不使用eval、exec函数。 实现思路:找到当前字符串优先级最高的表达式,在算术运算中,()优先级最高,则取出算式最底层的()...

python Django中的apps.py的目的是什么

This question has been asked earlier: 07000 Application configuration objects store metadata...

Python BeautifulSoup中文乱码问题的2种解决方法

解决方法一: 使用python的BeautifulSoup来抓取网页然后输出网页标题,但是输出的总是乱码,找了好久找到解决办法,下面分享给大家首先是代码复制代码 代码如下:from bs...

Python文件的读写和异常代码示例

一、从文件中读取数据 #!/usr/bin/env python with open('pi') as file_object: contents = file_object.r...

python requests使用socks5的例子

网络爬虫由于一个ip频繁访问同一网站,容易返回456或者被长时间封禁。 特别的本机有socks5客户端的设置如下,前提是已经安装了socks5的客户端软件,并且启动起来在固定端口为本机提...