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设计】。

相关文章

Python 基于Twisted框架的文件夹网络传输源码

Python 基于Twisted框架的文件夹网络传输源码

由于文件夹可能有多层目录,因此需要对其进行递归遍历。 本文采取了简单的协议定制,定义了五条命令,指令Head如下: Sync:标识开始同步文件夹 End:标识结束同步 File:标识传输...

Django 实现前端图片压缩功能的方法

思路: <img alt="" src="/img/图片真实地址" ></img> 上面是一个典型的HTML中的图片,在django中,src对应的path...

python算法与数据结构之冒泡排序实例详解

python算法与数据结构之冒泡排序实例详解

一、冒泡排序介绍   冒泡排序(英语:Bubble Sort)是一种简单的排序算法。它重复地遍历要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来。遍历数列的工作是重复地...

Python中实现远程调用(RPC、RMI)简单例子

远程调用使得调用远程服务器的对象、方法的方式就和调用本地对象、方法的方式差不多,因为我们通过网络编程把这些都隐藏起来了。远程调用是分布式系统的基础。 远程调用一般分为两种,远程过程调用(...

浅谈python下tiff图像的读取和保存方法

对比测试 scipy.misc 和 PIL.Image 和 libtiff.TIFF 三个库 输入: 1. (读取矩阵) 读入uint8、uint16、float32的lena.tif...