Python之time模块的时间戳,时间字符串格式化与转换方法(13位时间戳)

yipeiwu_com6年前Python基础

Python处理时间和时间戳的内置模块就有time,和datetime两个,本文先说time模块。

关于时间戳的几个概念

时间戳,根据1970年1月1日00:00:00开始按秒计算的偏移量。

时间元组(struct_time),包含9个元素。

time.struct_time(tm_year=2017, tm_mon=10, tm_mday=1, tm_hour=14, tm_min=21, tm_sec=57, tm_wday=6, tm_yday=274, tm_isdst=0) 

时间格式字符串,字符串形式的时间。

time模块与时间戳和时间相关的重要函数

time.time() 生成当前的时间戳,格式为10位整数的浮点数。

time.strftime()根据时间元组生成时间格式化字符串。

time.strptime()根据时间格式化字符串生成时间元组。time.strptime()与time.strftime()为互操作。

time.localtime()根据时间戳生成当前时区的时间元组。

time.mktime()根据时间元组生成时间戳。

示例

关于时间戳和格式化字符串的简单示例如下

import time

#生成当前时间的时间戳,只有一个参数即时间戳的位数,默认为10位,输入位数即生成相应位数的时间戳,比如可以生成常用的13位时间戳
def now_to_timestamp(digits = 10):
 time_stamp = time.time()
 digits = 10 ** (digits -10)
 time_stamp = int(round(time_stamp*digits))
 return time_stamp

#将时间戳规范为10位时间戳
def timestamp_to_timestamp10(time_stamp):
 time_stamp = int (time_stamp* (10 ** (10-len(str(time_stamp)))))
 return time_stamp

#将当前时间转换为时间字符串,默认为2017-10-01 13:37:04格式
def now_to_date(format_string="%Y-%m-%d %H:%M:%S"):
 time_stamp = int(time.time())
 time_array = time.localtime(time_stamp)
 str_date = time.strftime(format_string, time_array)
 return str_date

#将10位时间戳转换为时间字符串,默认为2017-10-01 13:37:04格式
def timestamp_to_date(time_stamp, format_string="%Y-%m-%d %H:%M:%S"):
 time_array = time.localtime(time_stamp)
 str_date = time.strftime(format_string, time_array)
 return str_date

#将时间字符串转换为10位时间戳,时间字符串默认为2017-10-01 13:37:04格式
def date_to_timestamp(date, format_string="%Y-%m-%d %H:%M:%S"):
 time_array = time.strptime(date, format_string)
 time_stamp = int(time.mktime(time_array))
 return time_stamp

#不同时间格式字符串的转换
def date_style_transfomation(date, format_string1="%Y-%m-%d %H:%M:%S",format_string2="%Y-%m-%d %H-%M-%S"):
 time_array = time.strptime(date, format_string1)
 str_date = time.strftime(format_string2, time_array)
 return str_date

实验

print(now_to_date())
print(timestamp_to_date(1506816572))
print(date_to_timestamp('2017-10-01 08:09:32'))
print(timestamp_to_timestamp10(1506816572546))
print(date_style_transfomation('2017-10-01 08:09:32'))

结果为

1506836224000
2017-10-01 13:37:04
2017-10-01 08:09:32
1506816572
1506816572
2017-10-01 08-09-32

以上这篇Python之time模块的时间戳,时间字符串格式化与转换方法(13位时间戳)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

将Emacs打造成强大的Python代码编辑工具

将Emacs打造成强大的Python代码编辑工具

基本配置 Emacs本身提供了python-mode,输入M-x python-mode,就可以进入python模式。相应地,会在菜单栏出现Python菜单。当然,一般来讲,如果是.py...

Python中的with...as用法介绍

这个语法是用来代替传统的try...finally语法的。 复制代码 代码如下: with EXPRESSION [ as VARIABLE] WITH-BLOCK 基本思想是wi...

Python工程师面试必备25条知识点

Python工程师面试必备25条Python知识点: 1.到底什么是Python?你可以在回答中与其他技术进行对比 下面是一些关键点: Python是一种解释型语言。这就是说,与C语言和...

解决Python设置函数调用超时,进程卡住的问题

背景: 最近写的Python代码不知为何,总是执行到一半卡住不动,为了使程序能够继续运行,设置了函数调用超时机制。 代码: import time import signal...

如何基于Python创建目录文件夹

这篇文章主要介绍了如何基于Python创建目录文件夹,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 Python对文件的操作还算是方便...