经常会用到时间处理及格式化,这里把方法做个集成,方便后续使用:
#!/usr/bin/env python
# -*-coding:utf-8-*-
from datetime import datetime as dt
import time
def string2timestamp(strValue):
try:
d = dt.strptime (strValue, "%Y-%m-%d %H:%M:%S")
t = d.timetuple ()
timeStamp = float (time.mktime (t))
# timeStamp = float(str(timeStamp) + str("%06d" % d.microsecond) ) /1000000
return timeStamp
except ValueError as e:
print e
d = dt.strptime (strValue, "%Y-%m-%d %H:%M:%S")
t = d.timetuple ()
timeStamp = int (time.mktime (t))
return timeStamp
def getCurrenttime():
#获取当前时间
try:
timeStamp = dt.now ()
date = timeStamp.strftime ("%Y-%m-%d %H:%M:%S")
# 2015-08-28 16:43:37.283000'
return date
except Exception as e:
print e
return 'failure'
def timestamp2string( timeStamp):
# 1440751417.283 --> '2019-08-28 16:43:37.283'
try:
d = dt.fromtimestamp(float(timeStamp)) # 做强制类型转换
date = d.strftime("%Y-%m-%d %H:%M:%S")
return date
except Exception as e:
print e
return 'failure'
if __name__ == '__main__':
timeStamp='1440751417.28'
print timestamp2string(timeStamp)
date='2020-08-13 12:25:42'
print string2timestamp(date)
print getCurrenttime()