Python 边做边学 8.6 工具类--时间工具(TimeUtil)

原文连接:http://blog.csdn.net/tomorrow13210073213/article/category/6931287

需求

前文说过,我们将时间转成时间戳存到数据库里,那就把处理时间的操作抽象一下,处理成工具;

  1. 获取指定时间的时间戳;
  2. 将时间戳转换成人可识别的格式(指定格式);
  3. 将字符串时间(指定格式)转换成时间戳;

Talk is cheap. Show me the code

import time


# 时间戳,到毫秒
def stamp_ms(c_time):
    if c_time is None:
        c_time = time.time()
    curr_t = int(c_time * 1000)
    return curr_t


# 格式化成2017-08-18
def fmt_date(c_time):
    return fmt_d(c_time, "%Y-%m-%d")


# 格式化成22:18:45
def fmt_time(c_time):
    return fmt_d(c_time, "%H:%M:%S")


# 格式化成2017-08-18 22:18:45
def fmt_datetime(c_time):
    return fmt_d(c_time, "%Y-%m-%d %H:%M:%S")


# 格式化成“fmt_str”指定格式
def fmt_d(c_time, fmt_str=None):
    if c_time is None:
        c_time = time.time()
    if fmt_str is None:
        fmt_str = "%Y-%m-%d %H:%M:%S"
    return time.strftime(fmt_str, time.localtime(c_time))


# 将字符串格式的时间转换成时间戳(单位毫秒)
def stamp_time(time_str, fmt_str=None):
    if time_str is None or len(time_str) == 0:
        return None
    if fmt_str is None:
        fmt_str = "%Y-%m-%d %H:%M:%S"
    try:
        timeArray = time.strptime(time_str, fmt_str)
        timeStamp = int(time.mktime(timeArray)) * 1000
        return timeStamp
    except Exception as e:
        print(e)
    return None

以上就是我们用到的时间工具类,需求相对比较简单,不再赘述;

以上内容仅供练习,学习使用;

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值