python之日期、时间处理方法

经常会用到时间处理及格式化,这里把方法做个集成,方便后续使用:

#!/usr/bin/env python
# -*-coding:utf-8-*-
from datetime import datetime as dt
import time

def string2timestamp(strValue):
    try:
        d = dt.strptime (strValue, "%Y-%m-%d %H:%M:%S")
        t = d.timetuple ()
        timeStamp = float (time.mktime (t))
        # timeStamp = float(str(timeStamp) + str("%06d" % d.microsecond) ) /1000000
        return timeStamp
    except ValueError as e:
        print e
        d = dt.strptime (strValue, "%Y-%m-%d %H:%M:%S")
        t = d.timetuple ()
        timeStamp = int (time.mktime (t))
        return timeStamp
    
def getCurrenttime():
    #获取当前时间
    try:
        timeStamp = dt.now ()
        date = timeStamp.strftime ("%Y-%m-%d %H:%M:%S")
        # 2015-08-28 16:43:37.283000'
        return date
    except Exception as e:
        print e
        return 'failure'

def timestamp2string( timeStamp):
    # 1440751417.283 --> '2019-08-28 16:43:37.283'
    try:
        d = dt.fromtimestamp(float(timeStamp)) # 做强制类型转换
        date = d.strftime("%Y-%m-%d %H:%M:%S")
        return date
    except Exception as e:
        print e
        return 'failure'

if __name__ == '__main__':
    timeStamp='1440751417.28'
    print timestamp2string(timeStamp)
    date='2020-08-13 12:25:42'
    print string2timestamp(date)
    print getCurrenttime()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值