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版

复制代码 代码如下:#coding:utf-8 import urllib.request import xml.dom.minidom import sqlite3 import th...

解决Django migrate No changes detected 不能创建表的问题

起因 修改了表结构以后执行python3 manage.py migrate 报错: django.db.utils.OperationalError: (1091, "Can't...

完美解决Pycharm无法导入包的问题 Unresolved reference

完美解决Pycharm无法导入包的问题 Unresolved reference

如下所示: Unresolved reference 'ERROR_CODE_INPUT_ERROR' less... (Ctrl+F1) This inspection dete...

python 调用有道api接口的方法

python 调用有道api接口的方法

初学python ,研究了几天,写了一个python 调用 有道api接口程序 效果看下图: 申明:代码仅供和我一样的初学者学习交流 有道api申请地址http://fanyi.you...

python实现统计代码行数的小工具

python实现统计代码行数的小工具

一个用python实现的统计代码行数的小工具,供大家参考,具体内容如下 实现功能 计算出某一目录以及子目录下代码文件的行数 在计算代码的过程中,只对标准命名的文件进行统计,如[...