zoukankan      html  css  js  c++  java
  • python中时间戳,datetime 和时间字符串之间得转换

    # datetime时间转为字符串
    def Changestr(datetime1):
        str1 = datetime1.strftime('%Y-%m-%d %H:%M:%S')
        return str1

    # 字符串时间转为时间戳
    def Changetime(str1):
        Unixtime = time.mktime(time.strptime(str1, '%Y-%m-%d %H:%M:%S'))
        return Unixtime

    # datetime时间转为时间戳
    def Changestamp(dt1):
        Unixtime = time.mktime(time.strptime(dt1.strftime('%Y-%m-%d %H:%M:%S'), '%Y-%m-%d %H:%M:%S'))
        return Unixtime

    # 时间戳转为datetime时间
    def Changedatetime(timestamp):
        dt = datetime.datetime.fromtimestamp(timestamp)
        return dt
    # uinx时间戳转换为本地时间
    def Localtime(datetime1):
        Localtime = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(datetime1))
        return Localtime

    # 字符串时间转换函数
    def Normaltime(datetime1):
        Normaltime = datetime.datetime.strptime(datetime1,'%Y-%m-%d %H:%M:%S')
        return Normaltime
     
    import time
    import datetime
    #  首先将时间字符串处理成标准的,即将小数位去掉
    time_stamp = "2019-04-10 00:30:10.198" .split('.')[0]
    
    #  将字符串转化为时间戳
    h =  time.mktime(time.strptime(time_stamp, "%Y-%m-%d %H:%M:%S"))
    
    #  将时间戳转换为字符串
    start_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(h-30))
    end_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(h+30))
    
    #  将时间字符串转化为datetime类型
    start_date = datetime.datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S")
    
    #  将时间戳转化为datetime类型
    t = datetime.datetime.fromtimestamp(h)
    print(t,type(t))
    
    
    print(start_date,type(start_date))
  • 相关阅读:
    老王python博客
    python中文分词
    python 字典(dict)get方法应用
    python yield和generators(生成器)
    python ASCII返回对应的值(chr)
    python 字符串特点
    python 包的定义,结构,导入过程
    fabric的安装和配置
    python 正则表达式re findall
    python unittest单元测试方法和用例
  • 原文地址:https://www.cnblogs.com/chaojiyingxiong/p/10764031.html
Copyright © 2011-2022 走看看