zoukankan      html  css  js  c++  java
  • 日期字串转为时间戳int

    日期字串转为时间戳int

    一、背景

    有时需要将日期字串:2016-05-05 20:28:54

    转为时间戳:1462451334。

    二、分析

    采用python,编写转换函数:date2time('2016-05-05 20:28:54') 

    返回时间戳:1462451334。

    三、封装好的函数方法

    import time
    
    
    # 日期字符串 => 时间戳int。只精确到秒。
    def date2time(date_str='2016-05-05 20:28:54', format='%Y-%m-%d %H:%M:%S'):
        '''
        日期字符串 转为 时间戳。精确到s,单位秒。
        输入举例说明:
        ('2016-05-05 20:28:54')
        ('2016-05-05 20:28:54','%Y-%m-%d %H:%M:%S')
        ('20160505 20:28:54','%Y%m%d %H:%M:%S')
        ('20160505 20_28_54','%Y%m%d %H_%M_%S')
        ('20160505','%Y%m%d')
        :param date_str:日期字符串
        :param format:输入日期字串的日期格式、样式
        :return:转换为int的时间戳。
        '''
        # 将时间字符串转为时间戳int
        dt = date_str
        # 转换成时间数组
        timeArray = time.strptime(dt, format)
        # 转换成时间戳
        timestamp = int(time.mktime(timeArray))
    
        return timestamp
    
    
    if __name__ == '__main__':
        date_str1 = '2016-05-05 20:28:54'
        format1 = '%Y-%m-%d %H:%M:%S'
        t1 = date2time(date_str1, format1)
        print(t1)
    
        date_str2 = '20160505'
        format2 = '%Y%m%d'
        t2 = date2time(date_str2, format2)
        print(t2)
    

      

    输出:

    1462451334
    1462377600

  • 相关阅读:
    告别被拒,如何提升iOS审核通过率(上篇)
    Linux 学习总结(二)
    Linux 学习总结(一)
    Navicat for mysql 破解
    IDEA2017-破解方法
    VmWare15 许可证
    Java 中的锁
    JVM 参数调优
    Tcp/Ip 三次握手与四次挥手
    Java 集合面试总结
  • 原文地址:https://www.cnblogs.com/andy9468/p/12627534.html
Copyright © 2011-2022 走看看