python timestamp和datetime之间转换详解

yipeiwu_com7年前Python基础

做开发中难免时间类型之间的转换, 最近就发现前端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 '' 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Django如何开发简单的查询接口详解

前言 Django处理json也是一把好手,有时候在工作中各个部门都会提供自己的相关接口,但是信息也只是单方的信息,这时候需要运维将各个部门的信息进行集成,统一出一个查询接口或页面,方便...

使用python Telnet远程登录执行程序的方法

如下所示: # -*-coding:utf-8 -*- def do_telnet(Host, username, password, finish, commands):...

PYTHON压平嵌套列表的简单实现

list 是 Python 中使用最频繁的数据类型, 标准库里面有丰富的函数可以使用。 不过,如果把多维列表转换成一维列表(不知道这种需求多不多),还真不容易找到好用的函数, 要知道...

基于Python和Scikit-Learn的机器学习探索

你好,%用户名%! 我叫Alex,我在机器学习和网络图分析(主要是理论)有所涉猎。我同时在为一家俄罗斯移动运营商开发大数据产品。这是我第一次在网上写文章,不喜勿喷。 现在,很多人想开...

关于pytorch中全连接神经网络搭建两种模式详解

pytorch搭建神经网络是很简单明了的,这里介绍两种自己常用的搭建模式: import torch import torch.nn as nn first: class NN...