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

相关文章

pytorch AvgPool2d函数使用详解

我就废话不多说了,直接上代码吧! import torch import torch.nn as nn import torch.nn.functional as F from to...

python操作kafka实践的示例代码

python操作kafka实践的示例代码

1、先看最简单的场景,生产者生产消息,消费者接收消息,下面是生产者的简单代码。 #!/usr/bin/env python # -*- coding: utf-8 -*- impor...

python实现多线程网页下载器

本文为大家分享了python实现的一个多线程网页下载器,供大家参考,具体内容如下 这是一个有着真实需求的实现,我的用途是拿它来通过 HTTP 方式向服务器提交游戏数据。把它放上来也是想大...

如何使用Python脚本实现文件拷贝

如何使用Python脚本实现文件拷贝

这篇文章主要介绍了如何使用Python脚本实现文件拷贝,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.实现目的 统一时间对服务器...

解决Python2.7读写文件中的中文乱码问题

Python2.7对于中文编码的问题处理的并不好,这几天在爬数据的时候经常会遇到中文的编码问题。但是本人对编码原理不了解,也没时间深究其中的原理。在此仅从应用的角度做一下总结, 1.设置...