python正常时间和unix时间戳相互转换的方法

yipeiwu_com6年前Python基础

本文实例讲述了python正常时间和unix时间戳相互转换的方法。分享给大家供大家参考。具体分析如下:

这段代码可以用来转换常规时间格式为unix时间戳,也可以将unix时间戳转换回来,
例如:1332888820 格式转换成 2012-03-28 06:53:40的形式

# -*- coding: utf-8 -*-
import time
def timestamp_datetime(value):
 format = '%Y-%m-%d %H:%M:%S'
 # value为传入的值为时间戳(整形),如:1332888820
 value = time.localtime(value)
 ## 经过localtime转换后变成
 ## time.struct_time(tm_year=2012, tm_mon=3, tm_mday=28, tm_hour=6, tm_min=53, tm_sec=40, tm_wday=2, tm_yday=88, tm_isdst=0)
 # 最后再经过strftime函数转换为正常日期格式。
 dt = time.strftime(format, value)
 return dt
def datetime_timestamp(dt):
  #dt为字符串
  #中间过程,一般都需要将字符串转化为时间数组
  time.strptime(dt, '%Y-%m-%d %H:%M:%S')
  ## time.struct_time(tm_year=2012, tm_mon=3, tm_mday=28, tm_hour=6, tm_min=53, tm_sec=40, tm_wday=2, tm_yday=88, tm_isdst=-1)
  #将"2012-03-28 06:53:40"转化为时间戳
  s = time.mktime(time.strptime(dt, '%Y-%m-%d %H:%M:%S'))
  return int(s)
if __name__ == '__main__':
 d = datetime_timestamp('2012-03-28 06:53:40')
 print d
 s = timestamp_datetime(1332888820)
 print s

PS:这里再为大家推荐一个本站Unix时间戳转换工具,附带了各种语言(Python/PHP/Java/MySQL等)Unix时间戳的操作方法:

Unix时间戳(timestamp)转换工具:http://tools.jb51.net/code/unixtime

希望本文所述对大家的Python程序设计有所帮助。

相关文章

python实现将一维列表转换为多维列表(numpy+reshape)

如题,我们直接使用numpy #!D:/workplace/python # -*- coding: utf-8 -*- # @File : numpy_reshape.py # @...

Python给图像添加噪声具体操作

Python给图像添加噪声具体操作

在我们进行图像数据实验的时候往往需要给图像添加相应的噪声,那么该怎么添加呢,下面给出具体得操作方法。 1、打开Python的shell界面,界面如图所示; 2、载入skimage工具包...

30秒轻松实现TensorFlow物体检测

Google发布了新的TensorFlow物体检测API,包含了预训练模型,一个发布模型的jupyter notebook,一些可用于使用自己数据集对模型进行重新训练的有用脚本。 使用该...

Python实现对字典分别按键(key)和值(value)进行排序的方法分析

本文实例讲述了Python实现对字典分别按键(key)和值(value)进行排序的方法。分享给大家供大家参考,具体如下: 方法一: #使用sorted函数进行排序 ''' sorte...

Python使用post及get方式提交数据的实例

最近在使用Python的过程中,发现网上很少提到在使用post方式时,怎么传一个数组作为参数的示例,此处根据自己的实践经验,给出相关示例: 单纯的post请求: def http_p...