自用python时间格式转换lib库代码

 1 #!/usr/bin/python
 2 #-*- coding:utf-8 -*-
 3 import time
 4 import datetime
 5 import pytz
 6 
 7 tz = pytz.timezone('Asia/Shanghai')
 8 
 9 def formatDatetime2Timestamp(dt):
10     return int(time.mktime(dt.timetuple()))
11 
12 def formatDatetime2Datestr(dt):
13     return "{0:0>2}-{1:0>2}-{2:0>2} {3:0>2}:{4:0>2}:{5:0>2}".format(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second)
14 
15 def formatDatestr2Datetime(datestr):
16     return tz.localize(datetime.datetime.strptime(datestr, "%Y-%m-%d %H:%M:%S"))
18 def formatDatestr2Timestamp(datestr): 19 return formatDatetime2Timestamp(formatDatestr2Datetime(datestr)) 20 21 def formatTimestamp2Datetime(timestamp): 22 timestamp = int(timestamp) 23 return tz.localize(datetime.datetime.fromtimestamp(timestamp))
24 25 def formatTimestamp2Datestr(timestamp): 26 timestamp = int(timestamp) 27 return datetime.datetime.strftime(formatTimestamp2Datetime(timestamp), "%Y-%m-%d %H:%M:%S") 28 29 def getCurDatetime(): 30 return datetime.datetime.now(tz) 31 32 def getOffsetDatetime(dt, second): 33 if second <= 0: 34 return dt - datetime.timedelta(seconds=second) 35 else: 36 return dt + datetime.timedelta(seconds=second) 37 38 def getCUrYear(): 39 return getCurDatetime().year 40 41 def getCurTimestamp(): 42 return formatDatetime2Timestamp(getCurDatetime())

 

posted on 2016-09-21 14:33  齐柏林飞艇  阅读(324)  评论(0编辑  收藏  举报