python 对于时间的处理 datetime str字符串 时间戳 相互转换

对于时间的处理

获取当前时间的datetime格式
datetime.datetime.now()

1. 将datetime格式转换为指定格式的str输出
datetime.strftime(start_time,"%Y-%m-%d %H:%M:%S")
# 这里的 start_time 是 数据库里的datetime格式

2. 将datetime格式转换为时间戳
start_time.replace(tzinfo=datetime.timezone.utc).timestamp()
# 或者
time.mktime(start_time.timetuple())
# 这里的 start_time 是 数据库里的datetime格式


3. 返回前端时将数据库内存的datetime格式转换为指定格式的str输出
models.TaskList.objects.filter(pk=task_id).first().active_time.strftime('%Y-%m-%d %H:%M:%S')

4. 获取当前时间戳
time.time()

5. 将字符串str转换为time模块能处理的struct_time格式
str_time = '2022-02-03 00:00:00'
time.strptime(str_time, '%Y-%m-%d %H:%M:%S')

6. 将字符串str转换成时间戳
time.mktime(time.strptime(str_time, "%Y-%m-%d %H:%M:%S"))

7. 将字符串str转换为datetime
datetime.datetime.strptime(str_time, "%Y-%m-%d %H:%M:%S")

8. 将时间戳转换为字符串str
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
# time.time() 是时间戳


    if len(wrong_corp_id_list) > 0:
        for i in wrong_corp_id_list:
            item = context.repo.vip_module.query().filter(VipModule.corp_id == i, VipModule.module == module_name).first()
            if item:
                item.expired_at = item.created_at + datetime.timedelta(days=7)
                print(item.created_at, item.expired_at)
            # db.session.commit()
posted @ 2020-10-13 17:48  Bitten  阅读(616)  评论(0编辑  收藏  举报