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

yipeiwu_com5年前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语法快速入门指南

Python语法快速入门指南

Python语言与Perl,C和Java等语言有许多相似之处。但是,也存在一些差异。 在本章中我们将来学习Python的基础语法,让你快速学会Python编程。 第一个Python程序...

Pandas时间序列重采样(resample)方法中closed、label的作用详解

Pandas提供了便捷的方式对时间序列进行重采样,根据时间粒度的变大或者变小分为降采样和升采样: 降采样:时间粒度变大。例如,原来是按天统计的数据,现在变成按周统计。降采样会涉及到...

Python中decorator使用实例

在我以前介绍 Python 2.4 特性的Blog中已经介绍过了decorator了,不过,那时是照猫画虎,现在再仔细描述一下它的使用。 关于decorator的详细介绍在 Python...

Python实现字典去除重复的方法示例

本文实例讲述了Python实现字典去除重复的方法。分享给大家供大家参考,具体如下: #!/usr/bin/env python # encoding: utf-8 #字典去重小代码...

用实例说明python的*args和**kwargs用法

先来看一个例子:复制代码 代码如下:>>> def foo(*args, **kwargs):    print 'args =', ar...