zoukankan      html  css  js  c++  java
  • python datetime timestamp

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

    Convert datetime to timestamp

    from datetime import datetime
    import time
    dt = datetime(2017,12,27,15,49)
    ts = time.mktime(dt.timetuple())
    print ts

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

    [python] view plain copy

    # '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  
    
    1. 时间戳转换成字符串日期时间

    [python] view plain copy

    # 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 ''
    人生当自勉,学习需坚持。从这一刻开始,我依旧是我,只是心境再不同。不论今后的路如何,我都会在心底默默鼓励自己,坚持不懈,等待那一场破茧的美丽。
  • 相关阅读:
    .NetCore(四) 在Nginx部署
    .Net Core(三)MVC Core
    .Net Core(二)EFCore
    .Net Core(一)环境搭建与基本使用
    Linux初体验
    Angular基础(八) Observable & RxJS
    Angular基础(七) HTTP & Routing
    Angular基础(六) DI
    Angular基础(五) 内建指令和表单
    Angular基础(四) 创建Angular应用
  • 原文地址:https://www.cnblogs.com/jiangqiuju/p/8125604.html
Copyright © 2011-2022 走看看