Contents
  1. 1. 时间戳 —> 时间字符串 ‘%Y-%m-%d %H:%M:%S’
  2. 2. 时间字符串 —> 时间戳 1407934120.0

原创作品,允许转载。转载时请务必以超链接形式标明文章原始出处、作者信息和本声明,否则将追究法律责任。

  • 连续空格替换为1个空格
1
2
s = ' 1 3 579'
s = ' '.join(s.split())


  • 获取文件名、当前路径、python所在路径
1
2
3
4
5
filename = os.path.basename(path_filename)
import os
import sys
print os.getcwd()
print sys.executable


  • 时间格式化
1
2
import time
time.strftime('%Y-%m-%d %H:%M:%S')
时间戳 —> 时间字符串 ‘%Y-%m-%d %H:%M:%S’
1
2
timestamp = time.time()
time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timestamp))
时间字符串 —> 时间戳 1407934120.0
1
2
str_time = "2014-08-13 20:48:40"
time.mktime(time.strptime(str_time, "%Y-%m-%d %H:%M:%S"))


  • 字典反转
1
2
from itertools import izip
dict(izip(d.itervalues(), d.iterkeys()))


  • 字典排序
1
2
3
4
5
6
7
def sortDict(adict):
l_keys = adict.keys()
l_keys.sort()
_dict = {}
for k in l_keys:
_dict[k] = adict[k]
return _dict


  • 合并字典
1
2
3
4
5
6
7
8
9
def merge_dict(d1, d2):
d3 = {}
for k,v in d1.iteritems():
d3[k] = v
for k,v in d2.iteritems():
if k in d3.keys():
print 'd1 & d2 has the same key.'
d3[k] = v
return d3


  • 判断文件或目录是否存在
1
2
3
import os
os.path.isfile('test.txt') #如果不存在就返回False
os.path.exists(directory) #如果目录不存在就返回False


  • 二分法查找/插入元素的index
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import bisect
L = [1,3,5,7,9]
x = 6
a = bisect.bisect_left(L, x)
b = bisect.bisect_right(L, x)
print a,b
x = 7
a = bisect.bisect_left(L, x)
b = bisect.bisect_right(L, x)
print a,b
L = [1,3,5,7,9]
a = bisect.insort_left(L, x)
print L
L = [1,3,5,7,9]
b = bisect.insort_right(L, x)
print L
Contents
  1. 1. 时间戳 —> 时间字符串 ‘%Y-%m-%d %H:%M:%S’
  2. 2. 时间字符串 —> 时间戳 1407934120.0