做开发中难免时间类型之间的转换, 最近就发现前端js和后端django经常要用到这个转换, 其中jsDate.now()精确到毫秒,而Python中Datetime.datetime.now()是精确到微秒的。

1. 字符串日期时间转换成时间戳

# '2015-08-28 16:43:37.283' --> 1440751417.283 
# 或者 '2015-08-28 16:43:37' --> 1440751417.0 
def string2timestamp(strValue): 
 
  try:     
    d = datetime.datetime.strptime(strValue, "%Y-%m-%d %H:%M:%S.%f") 
    t = d.timetuple() 
    timeStamp = int(time.mktime(t)) 
    timeStamp = float(str(timeStamp) + str("%06d" % d.microsecond))/1000000 
    print timeStamp 
    return timeStamp 
  except ValueError as e: 
    print e 
    d = datetime.datetime.strptime(str2, "%Y-%m-%d %H:%M:%S") 
    t = d.timetuple() 
    timeStamp = int(time.mktime(t)) 
    timeStamp = float(str(timeStamp) + str("%06d" % d.microsecond))/1000000 
    print timeStamp 
    return timeStamp 

2. 时间戳转换成字符串日期时间

# 1440751417.283 --> '2015-08-28 16:43:37.283' 
def timestamp2string(timeStamp): 
  try: 
    d = datetime.datetime.fromtimestamp(timeStamp) 
    str1 = d.strftime("%Y-%m-%d %H:%M:%S.%f") 
    # 2015-08-28 16:43:37.283000' 
    return str1 
  except Exception as e: 
    print e 
    return '' 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com