脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python基于datetime或time模块分别获取当前时间戳的方法实例

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

2021-05-30 00:43Together_CZ Python

今天小编就为大家分享一篇关于Python基于datetime或time模块分别获取当前时间戳的方法实例,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧

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

?
1
2
3
4
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

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

?
1
2
3
4
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

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

?
1
2
3
4
5
6
7
8
9
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

PS:给大家分享一款在线时间戳转换工具 https://tool.zzvips.com/t/timestamp/

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对服务器之家的支持。如果你想了解更多相关内容请查看下面相关链接

原文链接:https://blog.csdn.net/Together_CZ/article/details/85256753

延伸 · 阅读

精彩推荐