python时间戳与日期互转

作者: the5fire 标签: python time python工具箱 python时间戳 发布: 2012-09-19 阅读: 21584
因为总是会有这个需求,每次用的时候都是上网上现查,觉得很费事,不如封装成自己的函数放到工具库里。


#coding:utf-8

__author__ = 'the5fire'

'''
parse time
'''

import time

def time2stamp(timestr, format_type='%Y-%m-%d %H:%M:%S'):
return time.mktime(time.strptime(timestr, format_type))

def stamp2time(stamp, format_type='%Y-%m-%d %H:%M:%S'):
return time.strftime(format_type, time.localtime(stamp))


if __name__ == '__main__':
stamp = time.time()
nowtime = stamp2time(stamp)
print stamp, '-->', nowtime
print
stamp = time2stamp(nowtime)
print nowtime, '-->', stamp
print
print stamp, '-->', stamp2time(stamp)

---- EOF ----

微信公众号:Python程序员杂谈

相关文章