python 时间函数处理

前端如果传入 时间函数为 str = 1919-12-03
那么存入到数据库之中的为
from datetime import datetime
datetime.strptime(dir_data['bpub_date'], '%Y-%m-%d').date()
时间函数的相加减:
1,timedelta内部只能存储days,seconds,microseconds(毫秒),minutes
2,如果想要获取其他时间,需要转换 比如 10分钟 = minutes* 10
    # 获取当前时间
    now=datetime.datetime.now()
    str(now)
    # 当前时间的前一天
    pro_now = now - datetime.timedelta(days=1)
    str(now)
    # 当期时间的前一个小时
    end_now = now - datetime.timedelta(hours=1)
    str(end_now)
    # 当前时间的 后10分钟
    end_now = now + datetime.timedelta(minutes=10)
    # 并且格式化输出!
    end_now.strftime("%Y-%m-%d %H:%M:%S")
时间戳与字符串之间的转换
import time

#将 日期字符串 转成 struct时间对象格式
string_2_struct = time.strptime("2016/05/22","%Y/%m/%d")
print(string_2_struct)
#将struct时间对象转成时间戳
struct_2_stamp = time.mktime(string_2_struct)
print(struct_2_stamp)

# 将时间戳转为字符串格式
print(time.gmtime(time.time()-86640)) #将utc时间戳转换成struct_time格式
print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #将utc struct_time格式转成指定的字符串格式
from datetime import datetime
import time
from django.utils import timezone
# expire_time 是时间戳 精确到毫秒
if expire_time is not None:
    expire_time = datetime.fromtimestamp(
            # 此处精确到秒
            expire_time / 1000, timezone.get_current_timezone()
        )
    # 将当前时间改为 23:59:59秒
    expire_time =datetime.fromtimestamp(
        time.mktime(
            datetime(
                expire_time.year,
                expire_time.month,
                expire_time.day, 23, 59, 59
            ).timetuple()
        ), timezone.get_current_timezone()   #get_current_timezone() 转换成什么格式的时间 自动获取,你可以手动设置
        )

 


时间戳 - utc - datetime - 时间戳- utc
posted @ 2018-06-15 11:38  十七楼的羊  阅读(214)  评论(0编辑  收藏  举报